<?php
/**
 * Created by PhpStorm.
 * User: xianxuefeng
 * Date: 2018/5/24
 * Time: 14:07
 */
namespace app\controllers\crontab;
use Yii;
use app\models\Elog;
use app\models\marketing\MailSendlist;

class AnalysisMailGroupController  extends \app\base\Controller
{
    /**
     * redis连接
     * @var object
     */
    private $pageSize =20000;
    private $batchSize  = 200;
    private $updateOrderSize = 50;
    private $openDiviceName= [
        '0' =>'other',
        '1' => 'ios',
        '2' => 'android',
        '3' => 'pc',
        '4' => 'pad',
        '5' => 'wap'
    ];
    private $singleDeviceName =
        [
            '0' =>'other',
            '1' => 'ios',
            '2' => 'android',
            '3' => 'pc',
            '4' => 'pad',
            '5' => 'wap'
        ];
    private $gearbestOrderDeviceType = [
        '0' => '0',    // 不属于这个区间的为其它类型other
        '1' => '3',   //web => pc
        '2' => '5',
        '3' => '1',
        '4' => '2',
        '5' => '4'
    ];

    private $otherOrderDeviceType = [
        '0' => '0',    // 不属于这个区间的为其它类型other
        '1' => '5',   //web => pc
        '2' => '1',
        '3' => '2'
    ];
    private $mongodsn;
    private $mongo;    //初始化信息
    private $mongodb;   //选中数据库信息
    private $prefix = 'funnel_analysis_group_id_';
    private $table;
    private $res_backup = 'funnel_analysis_response_back';   //数据分析响应备份
    private $analysis_schedule  = 'funnel_analysis_schedule';        // 数据分析执行进度
    private $analysis_back_schedule  = 'funnel_analysis_back_schedule';        // 数据分析执行进度
    private $sys_status = 'analysis_status';    // 数据分析同步状态
    private $time ='0';
    private function error($msg = '系统繁忙') {
        if (empty($msg)) {
            $msg = '系统繁忙';
        }
        exit(json_encode(['status' => 0,'msg' => $msg,'data' => []]));
    }
    private function success($data = [],$msg = '成功') {
        exit(json_encode(['status' => 1,'msg' => $msg,'data' =>$data]));
    }

    public function init() {
        $this->time = date("m-d") ;

        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。
        $this->mongodsn  =  yii::$app->mongodb->dsn;
    }

    /*
     *  $m 连接信息
     *  $db
     */
    public function initMongo() {
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。
        $this->mongodsn  =  yii::$app->mongodb->dsn;
        $replicaSet = isset(yii::$app->mongodb->replicaSet) ? yii::$app->mongodb->replicaSet : null;

        try {
            if (!empty($this->mongo)) {
                self::destroyMongo();
            }
            if (!empty($replicaSet)) {
                $this->mongo = new \MongoClient($this->mongodsn, array("replicaSet" => $replicaSet,'connectTimeoutMS'=>300000));
            } else {
                $this->mongo = new \MongoClient($this->mongodsn);
            }
            $databaseName = trim(strrchr($this->mongodsn, "/"), "/");   //获取配置信息中，/后面的库名
            $this->mongodb = $this->mongo->$databaseName;
            if (empty($this->mongodb)) {
                exit(json_encode(['status' => 0, 'msg' => 'mongodb 连接失败，请稍候再试', 'data' => []]));
                Elog::logCrontab($msg, "analysisMailGroup_{$this->time}", "info");
            }
        }  catch (\Exception $e) {
            $msg = "initMongo  catch information " . $e->getMessage();
            Elog::logCrontab($msg, "analysisMailGroup_{$this->time}", "info");
        }
    }

    /**
     *  $m 摧毁mongodb连接信息
     */
    public function destroyMongo() {
        if (empty($this->mongo)) {
            return ;
        }
        $res = $this->mongo->close();
        if (! empty($res)) {
            $this->mongo = null;
        }
        $this->mongodb = null;
    }

    /**
     *
     * 是否要同步数据
     */
    private function whetherToSynchronize($index='analysis_back_completed') {
        self::initMongo();   //初始化mongo
        $table = $this->sys_status;
        $collection = $this->mongodb->$table;
        $sch= $collection->find([],['_id'=>0]);
        $analysis_back_completed = [];
        if ( ! empty($sch)) {
            $analysis_back_completed = iterator_to_array($sch)[0];
        }
        //已经同步完成了，不需要在同步
        if (! isset($analysis_back_completed[$index]) || ! empty($analysis_back_completed[$index]) ) {
            return false;
        }
        self::destroyMongo();
        return true;
    }

    /**
     *  收集信息同步到mongodb
     * /crontab/analysis-mail-group/user-label?module_name=marketing_email
     */
    public function collectInfoSys ($groupId=0)
    {
        $status = self::whetherToSynchronize('syn_analysis_completed');
        if (empty($status)) {
            return ;
        }
        $site_list =  Yii::$app->params['sites']['marketing_email']['web_index'];
        date_default_timezone_set('Asia/Shanghai');
        $yesterdayTimeStamp = strtotime("-1 day");       //获取前一天的时间戳
//        $lastmonthTimeStamp = strtotime("last month");    //获取一个月前的时间戳
        $lastmonthTimeStamp = strtotime("-18 day");    //获取一个月前的时间戳

        // 备份执行group_id 和mail_sendlist_* 进度.collectInfoSys...funnel_analysis_schedule
        if (!empty($groupId)) {

            $analysisSchedule = self::getAnalysisSchedule($groupId);
        } else {
        $analysisSchedule = self::getAnalysisSchedule();
        }

        if (! empty($analysisSchedule) && isset($analysisSchedule['group_id'])) {
            $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_id <= {$analysisSchedule['group_id']} and group_last_send between  $lastmonthTimeStamp and  $yesterdayTimeStamp order by group_id desc";
        } elseif(!empty($groupId)) {
            $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_id = {$groupId}";
        } else {
            $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_last_send between  $lastmonthTimeStamp and  $yesterdayTimeStamp order by group_id desc";
        }
        $mailGroupList = yii::$app->db->createCommand($sql)->queryAll();
        Elog::logCrontab("\n\n start the syn-sendlist-to-mongodb method ,sql {$sql}.... \n","analysisMailGroup_{$this->time}","info");

        foreach ( $mailGroupList as $val ) {
            if (!isset($site_list[$val['site_id']])) {
                continue;
            }
            self::initMongo();   //初始化mongo
            $val['site_name'] = $site_list[$val['site_id']];
            $table = $this->table = $this->prefix . $val['group_id'];
            $collection = $this->mongodb->$table;      //选择聚合
            $msg = "\nchoose table $table \n";
            Elog::logCrontab($msg, "analysisMailGroup_{$this->time}", "info");
            //如果存在此集合就则删除
            // continue;
            $exist = $collection->count();
            self::destroyMongo();
            if (empty($exist) || isset($analysisSchedule['synSendEmail']['id'])) {
                self::synSendEmail($val);          // 邮件，邮件类型
//                self::delAnalysisSchedule();        //删除执行成功的分组
            }
            self::resetAnalysisSchedule($val['group_id']);    //记录执行中的group_id
            //self::synSendEmail($val);          // 邮件，邮件类型
            self::synUnsubscribe($val);         // 退订，硬弹，软弹，点击
            self::synOrder($val);                  // 订单，商品，订单终端
            self::synChick($val);               // 打开信息
            self::updateAnalysisBack($val['group_id']);     //备份数据

        }
        self::initMongo();
        $table = $this->sys_status;
        $collection = $this->mongodb->$table;      //选择聚合
        $collection->update([],
            ['$set' =>                              // 更新内容
                ['syn_analysis_completed' => true] //更新完成了
            ], ['upsert'=>true]);
        self::destroyMongo();
        self::delAnalysisSchedule();        //删除执行成功的分组
        Elog::logCrontab("\n\n end  the syn-sendlist-to-mongodb method ........\n\n","analysisMailGroup_{$this->time}","info");
        exit("\n\n done.....\n");
    }

    /**
     *  收集信息同步到mongodb
     * /crontab/analysis-mail-group/user-label?module_name=marketing_email
     */
    public function threeDayUpdate ()
    {
        $status = self::whetherToSynchronize('syn_analysis_week_completed');

        if (empty($status)) {
            return ;
        }
        $site_list =  Yii::$app->params['sites']['marketing_email']['web_index'];
        date_default_timezone_set('Asia/Shanghai');
//        $yesterdayTimeStamp = strtotime("-1 day");       //获取前一天的时间戳
        $lastmonthTimeStamp = strtotime("-3 day");    //获取三条前的时间戳
        $analysisSchedule = self::getAnalysisSchedule();

        if (! empty($analysisSchedule) && isset($analysisSchedule['group_id'])) {
            $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_id <= {$analysisSchedule['group_id']} and group_last_send >=  $lastmonthTimeStamp order by group_id desc";
        } else {
            $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_last_send >=  $lastmonthTimeStamp  order by group_id desc";
        }

        $mailGroupList = yii::$app->db->createCommand($sql)->queryAll();
        Elog::logCrontab("\n\n start the three-day-update method ,sql {$sql}.... \n","analysisMailGroup_{$this->time}","info");

        foreach ( $mailGroupList as $val ) {
            if (!isset($site_list[$val['site_id']])) {
                continue;
            }
            self::initMongo();   //初始化mongo
            $val['site_name'] = $site_list[$val['site_id']];
            $table = $this->table = $this->prefix . $val['group_id'];
            $collection = $this->mongodb->$table;      //选择聚合
            $msg = "\nchoose table $table \n";
            Elog::logCrontab($msg, "analysisMailGroup_{$this->time}", "info");
            //如果存在此集合就则删除
            // continue;
            $exist = $collection->count();
            self::destroyMongo();

            if (empty($exist) || isset($analysisSchedule['synSendEmail']['id'])) {
                self::synSendEmail($val);          // 邮件，邮件类型
            }
            self::resetAnalysisSchedule($val['group_id']);    //记录执行中的group_id
            self::synUnsubscribe($val);
            self::synOrder($val);                  // 订单，商品，订单终端
            self::synChick($val);               // 用户点击，点击设备
            self::updateAnalysisBack($val['group_id']);     //备份数据
        }
        self::initMongo();
        $table = $this->sys_status;
        $collection = $this->mongodb->$table;      //选择聚合
        $collection->update([],
            ['$set' =>                              // 更新内容
                ['syn_analysis_week_completed' => true] //更新完成了
            ], ['upsert'=>true]);
        self::destroyMongo();
        self::delAnalysisSchedule();        //删除执行成功的分组
        Elog::logCrontab("\n\n end  the three-day-update method ........\n\n","analysisMailGroup_{$this->time}","info");
        exit("\n\n done.....\n");
    }


    /**
     *  更新4天前的数据
     *
     */
    public function actionUpdateThreeDayInfo() {
        ignore_user_abort(true);
        set_time_limit(0);
        $fp = fopen(ROOT_PATH."/analysismailgroup_lock.txt", "r");
// 加锁（如果改成flock($fp, LOCK_EX | LOCK_NB)，demo2.php会直接返回2，否则会等待demo.php执行完返回1）
        if(flock($fp, LOCK_EX | LOCK_NB))
        {
            self::threeDayUpdate();
            flock($fp,LOCK_UN);
            fclose($fp);  //关闭文件
            exit("\n\n done.....\n");
        }
        fclose($fp);  //关闭文件
        exit("\n\t busy...\n");
    }

    /**
     *  四天数据更新
     *
     */
    public function actionOpenThreeSynch() {
        self::initMongo();
        $table = $this->sys_status;
        $collection = $this->mongodb->$table;      //选择聚合
        $collection->update([],
            ['$set' =>                             // 更新内容
                ['syn_analysis_week_completed' => false ]     // 未同步
            ], ['upsert'=>true]);
//        更新完成后删除跟踪信息
        self::destroyMongo();
        exit("\n\n done.....\n");
    }



    /**
     *  同步邮件信息
     *
     */
    public function actionSysMailInfo() {
        ignore_user_abort(true);
        set_time_limit(0);
        $fp = fopen(ROOT_PATH."/analysismailgroup_lock.txt", "r");
// 加锁（如果改成flock($fp, LOCK_EX | LOCK_NB)，demo2.php会直接返回2，否则会等待demo.php执行完返回1）
        if(flock($fp, LOCK_EX | LOCK_NB))
        {

            $mothod = strtolower(Yii::$app->request->getMethod());
            $groupId = Yii::$app->request->$mothod('group_id');
            if (!empty($groupId)) {
                self::collectInfoSys($groupId);
            } else {
            self::collectInfoSys();
            }
            flock($fp,LOCK_UN);
            fclose($fp);  //关闭文件
            exit("\n\n done.....\n");
        }
        fclose($fp);  //关闭文件
        exit("\n\t busy...\n");
    }

    /**
     *  更新数据分析备份
     *
     */
    public function synUpdateAnalysisBack() {

        $status = self::whetherToSynchronize('analysis_back_completed');
        if (empty($status)) {
            return ;
        }

        date_default_timezone_set('Asia/Shanghai');
        $yesterdayTimeStamp = strtotime("-1 day");       //获取前一天的时间戳
        $lastmonthTimeStamp = strtotime("last month");    //获取一个月前的时间戳
        // 备份执行group_id 和mail_sendlist_* 进度.collectInfoSys...funnel_analysis_schedule
        self::initMongo();   //初始化mongo
        $table = $this->analysis_back_schedule;
        $collection = $this->mongodb->$table;      //选择聚合
        $analysisSchedule= $collection->find([],['_id'=>0]);
        $analysisSchedule = iterator_to_array($analysisSchedule);
        if (isset($analysisSchedule[0]) && ! empty($analysisSchedule[0])) {
            $analysisSchedule = $analysisSchedule[0];
        }
        self::destroyMongo();
        if (! empty($analysisSchedule) && isset($analysisSchedule['group_id'])) {
            $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_id <= {$analysisSchedule['group_id']} and group_last_send between  $lastmonthTimeStamp and  $yesterdayTimeStamp order by group_id desc";
        } else {
            $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_last_send between  $lastmonthTimeStamp and  $yesterdayTimeStamp order by group_id desc";
        }
        $mailGroupList = yii::$app->db->createCommand($sql)->queryAll();
        Elog::logCrontab("\n\n start the UpdateAnalysisBack method  action sql {$sql}.... \n","analysisMailGroup_{$this->time}","info");
        foreach ( $mailGroupList as $val ) {
            self::initMongo();   //初始化mongo
            $this->table = $this->prefix . $val['group_id'];
            $table = $this->analysis_back_schedule;
            $collection = $this->mongodb->$table;      //选择聚合
            $collection->update([],
                ['$set' =>                             // 更新内容
                    ['group_id' => $val['group_id']]
                ], ['upsert'=>true]);
            self::destroyMongo();
            self::updateAnalysisBack($val['group_id']);     //备份数据
        }
        self::initMongo();
        $table = $this->sys_status;
        $collection = $this->mongodb->$table;      //选择聚合
        $collection->update([],
            ['$set' =>                             // 更新内容
                ['analysis_back_completed' => true]
            ], ['upsert'=>true]);
//        更新完成后删除跟踪信息
        $table = $this->analysis_back_schedule;
        $collection = $this->mongodb->$table;      //选择聚合
        $collection->drop();
        self::destroyMongo();
        Elog::logCrontab("\n\n end  theUpdateAnalysisBack method ........\n\n","analysisMailGroup_{$this->time}","info");
        exit("\n\n done.....\n");
    }

    public function actionSynUpdateAnalysisBack() {
        ignore_user_abort(true);
        set_time_limit(0);
        $fp = fopen(ROOT_PATH."/update_analysis_back_lock.txt", "r");
// 加锁（如果改成flock($fp, LOCK_EX | LOCK_NB)，demo2.php会直接返回2，否则会等待demo.php执行完返回1）
        if(flock($fp, LOCK_EX | LOCK_NB))
        {
            self::synUpdateAnalysisBack();
            flock($fp,LOCK_UN);
            fclose($fp);  //关闭文件
            exit("\n\n done.....\n");
        }
        fclose($fp);  //关闭文件
        exit("\n\t busy...\n");
    }

    /**
     *  开启数据同步，一天执行一次
     *
     */
    public function actionOpenSynch() {
        self::initMongo();
        $table = $this->sys_status;
        $collection = $this->mongodb->$table;      //选择聚合
        $collection->update([],
            ['$set' =>                             // 更新内容
                ['analysis_back_completed' => false,   //未同步
                    'syn_analysis_completed' => false]     // 未同步
            ], ['upsert'=>true]);
//        更新完成后删除跟踪信息
        self::destroyMongo();
        exit("\n\n done.....\n");
    }

    /**
     * @throws \yii\db\Exception
     * 清除老数据
     *
     */
    public function actionCleanUpData() {
        ignore_user_abort(true);
        set_time_limit(0);
        $site_list =  Yii::$app->params['sites']['marketing_email']['web_index'];
        // 备份执行group_id 和mail_sendlist_* 进度.collectInfoSys...funnel_analysis_schedule
//            $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
//site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_last_send  order by group_id desc";
        $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,track_code from mail_group where group_last_send  order by group_id desc";
        $mailGroupList = yii::$app->db->createCommand($sql)->queryAll();
        foreach ( $mailGroupList as $val ) {
            if (!isset($site_list[$val['site_id']])) {
                continue;
            }
            self::initMongo();   //初始化mongo
            $val['site_name'] = $site_list[$val['site_id']];
            $table = $this->table = $this->prefix . $val['group_id'];
            $collection = $this->mongodb->$table;      //选择聚合
            $msg = "\nchoose table $table \n";
            Elog::logCrontab($msg, "analysisMailGroup_{$this->time}", "info");
            //如果存在此集合就则删除
            // continue;
            $collection->drop();
            self::destroyMongo();
        }
        self::delAnalysisSchedule();

        self::initMongo();
        $table = $this->res_backup;
        $collection  =$this->mongodb->$table;
        $collection->drop();
        self::destroyMongo();
        exit("\n\t Clean up success...\n");
    }

    public function actionGetMailGroupInfo() {
        ignore_user_abort(true);
        set_time_limit(0);
        $post = $_REQUEST;
        if (! isset($post['type'])) {
            exit("\n\n Error of parameters.....\n");
        }
        if ( ! isset($post['start_time']) || isset($post['end_time'])) {
            date_default_timezone_set('Asia/Shanghai');
            $post['end_time'] = strtotime("-1 day");     //获取前一天的时间戳
            $post['start_time'] = strtotime("last month");  //获取一个月前的时间戳
        }
        $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_last_send between  {$post['start_time']} and  {$post['end_time']} order by group_id desc";
        $mailGroupList = yii::$app->db->createCommand($sql)->queryAll();
        if (empty($mailGroupList)) {
            exit("\n\n No more dataNo more data.....\n");
        }
        // 或则写入redis 备份

    }

    /*
     *  邮件分析数据同步到mongodb
     *
     */
    public function actionSynEmailAnalysisMongodb() {
        ignore_user_abort(true);
        set_time_limit(0);
        $post = $_REQUEST;
        if (! isset($post['type']) || ! isset($post['start_time']) || isset($post['end_time'])) {
            exit("\n\n Error of parameters.....\n");
        }
        $site_list =  Yii::$app->params['sites']['marketing_email']['web_index'];
        //获取前一天的时间戳
        //获取一个月前的时间戳
//        date_default_timezone_set('Asia/Shanghai');
//        $yesterdayTimeStamp = strtotime("-1 day");
//        $lastmonthTimeStamp = strtotime("last month");
//        $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
//site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_last_send between  $lastmonthTimeStamp and  $yesterdayTimeStamp order by group_id desc";
        $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,track_code from mail_group where  is_inside_test = 0 and state = 2 and group_last_send between  {$post['start_time']} and  {$post['end_time']} order by group_id desc";

        $mailGroupList = yii::$app->db->createCommand($sql)->queryAll();
        Elog::logCrontab("\n\n start the syn-sendlist-to-mongodb method .... \n","analysisMailGroup_{$this->time}","info");
        foreach ( $mailGroupList as $val ) {
            if (!isset($site_list[$val['site_id']])) {
                continue;
            }
            switch ($post['type']) {
                case "synSendEmail":
                    self::initMongo();   //初始化mongo
                    $val['site_name'] = $site_list[$val['site_id']];
                    $table = $this->table = $this->prefix . $val['group_id'];
                    $collection = $this->mongodb->$table;      //选择聚合
                    $exist = $collection->count();
                    $collection->drop();
                    self::destroyMongo();
                    if (empty($exist)) {
                        self::synSendEmail($val,$val);          // 邮件，邮件类型
                    }
                    break;
                case "synUnsubscribe":
                    self::synUnsubscribe($val);      // 退订信息
                    break;
                case "synOrder":
                    self::synOrder($val);            // 订单，商品，订单终端
                    break;
                case "synChick":
                    self::synChick($val);             // 用户点击，点击设备
                    break;
                case "updateAnalysisBack":
                    self::updateAnalysisBack($val['group_id']);     //备份数据
                    break;
                default :
                    break;
            }
        }

        Elog::logCrontab("\n\n end  the syn-sendlist-to-mongodb method ........\n\n","analysisMailGroup_{$this->time}","info");
        exit("\n\n done.....\n");
    }

    private function getmailGroupSendCount($group_id) {
        $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,have_send_test,track_code from mail_group where group_id = $group_id";
        $mailGroupList = yii::$app->db->createCommand($sql)->queryAll();
        if (empty($mailGroupList)) {
            return 0;
        }
        return $mailGroupList[0]['send_ok_count'];
    }

    private function updateAnalysisBack($group_id) {

        //获取备份数据
        $insertInfo = self::totalTransformation(['group_id'=>$group_id]);
        $insertInfo['group_id'] = $group_id;
        $table = $this->res_backup;
        self::initMongo();
        $collection  =$this->mongodb->$table;
        $res = $collection->update(['group_id' => $group_id],
            ['$set' =>                             // 更新内容
                $insertInfo
            ], ['upsert'=>true]);
        self::destroyMongo();
        if (  empty($res['nModified'])) {
            Elog::logCrontab("\n\n in  the updateAnalysisBack method ，
            Insert data to a aggregation failure, data information :  ".\GuzzleHttp\json_encode($insertInfo)."\n\n","analysisMailGroup_{$this->time}","info");
        }
        return ;
    }

    /**
     * @param $group_id
     * @param $info['synSendEmail' =>['user_id' =>'记录上次user_id执行成功的最后值']]
     *
     */
    private function updateAnalysisSchedule($group_id,$info=[]) {
        // 备份执行group_id 和mail_sendlist_* 进度.collectInfoSys...funnel_analysis_schedule
        if (empty($group_id)) {
            Elog::logCrontab("\n\n in  the updateAnalysisSchedule method ，
            param information :  ".\GuzzleHttp\json_encode($group_id)."\n\n","analysisMailGroup_{$this->time}","info");
            return false;
        }
        if (empty($info)) {
            $info['group_id'] = $group_id;
        }
        $table = $this->analysis_schedule;
        self::initMongo();
        $collection  =$this->mongodb->$table;
        $res = $collection->update(['group_id' => $group_id],
            ['$set' =>                             // 更新内容
                $info
            ], ['upsert'=>true]);
        self::destroyMongo();
        if (  empty($res['nModified'])) {
            Elog::logCrontab("\n\n in the updateAnalysisSchedule method ，
            update {$group_id} failed:  ".\GuzzleHttp\json_encode($info)."\n\n","analysisMailGroup_{$this->time}","info");
        }
        return true;
    }

    public function resetAnalysisSchedule($group_id) {
        if (empty($group_id)) {
            Elog::logCrontab("\n\n in  the resetAnalysisSchedule method ，
            param information :  ".\GuzzleHttp\json_encode($group_id)."\n\n","analysisMailGroup_{$this->time}","info");
            return false;
        }
        $table = $this->analysis_schedule;
        self::initMongo();
        $collection  =$this->mongodb->$table;
        $collection->drop();
        $res = $collection->update([],
            ['$set' =>                             // 更新内容
                ['group_id' => $group_id,'time'=>time()]
            ], ['upsert'=>true]);
        self::destroyMongo();
//        if (  empty($res['nModified'])) {
//            Elog::logCrontab("\n\n in the resetAnalysisSchedule method ，
//            update {$group_id} failed: \n\n","analysisMailGroup_{$this->time}","info");
//        }
    }
    public function actionTestab() {
        $params = $_REQUEST;
        $group_id = "1111";
        if ( isset($params['group_id']) && ! empty($params['group_id'])) {
            $group_id = $params['group_id'];
        }
        self::resetAnalysisSchedule($group_id);
    }
    /**
     * @param $group_id
     * 获取当前执行的进度
     * response :
     * [
     * 'group_id' => '分组id值',
     * 'synSendEmail' => ['user_id'=>'$user_id'],
     * ...
     * ]
     *
     */
    private function getAnalysisSchedule($group_id = null) {
        $cond = [];
        if (! empty($group_id)) {
            $cond['group_id'] = $group_id;
        }
        $table = $this->analysis_schedule;
        self::initMongo();
        $collection  =$this->mongodb->$table;
        $resInfo = $collection->find($cond,['_id'=>0]);
        self::destroyMongo();
        $res = iterator_to_array($resInfo);
        if (empty($res) || ! isset($res[0])) {
            return [];
        }
        return $res[0];
    }

    /**
     * @param null $group_id
     * @return 0|array
     */
    private function delAnalysisSchedule() {

        $table = $this->analysis_schedule;
        self::initMongo();
        $collection  =$this->mongodb->$table;
        $collection->drop();
        self::destroyMongo();
    }



    public function actionSynunsubMongodb ()
    {
        ignore_user_abort(true);
        set_time_limit(0);
        $post = $_REQUEST;
        if (! isset($post['group_id'])) {
            $post['group_id'] = 10920;
        }
        if (isset($post['pagesize'])) {
            $this->pageSize = $post['pagesize'];
        }
        $group_id = $post['group_id'];
        ignore_user_abort(true);
        set_time_limit(0);
        $site_list =  Yii::$app->params['sites']['marketing_email']['web_index'];
        $sql = "select group_id,group_name,send_ok_count,send_status_fail_count,
site_id,have_send_test,track_code from mail_group where  group_id = $group_id";
        $mailGroupList = yii::$app->db->createCommand($sql)->queryAll();
        if (empty($mailGroupList)) {
            exit("No more data");
        }
        $temp = $mailGroupList['0'];
        $temp['site_name'] = $site_list[$temp['site_id']];
        $table = $this->table = $this->prefix.$temp['group_id'];
        self::initMongo();
        $m =  $this->mongodb; // 获取名称为 "test" 的数据库
        $collection = $m->$table;
        Elog::logCrontab("\n\n start the synunsub-mongodb .... \n","analysisMailGroup_{$this->time}","info");
        if (isset($post['back'])) {
            self::updateAnalysisBack($group_id);     //备份数据
            exit("done....");
        }
        if (isset($post['type'])) {
            $collection->drop();
            self::synSendEmail($temp);
        }
        self::synOrder($temp);                 // 订单，商品，订单终端
        self::synUnsubscribe($temp);
        self::synChick($temp);                 // 用户点击，点击设备
        Elog::logCrontab("\n\n end the synunsub-mongodb .......\n\n","analysisMailGroup_{$this->time}","info");
        exit("done....");
    }




    /*
     *  取消订阅
     *
     */
    private function synUnsubscribe($info) {
        Elog::logCrontab("\t go in  synUnsubscribe method info" .\GuzzleHttp\json_encode($info) . "\n","analysisMailGroup_{$this->time}","info");

        //退订信息收集
        $pageStart = 0;
        $offset = 0;
        //邮件退订
        while(true) {
            $sql = "select email,is_hard_bounces,is_soft_bounces,is_unsubscribe,is_click,is_complaint from mail_trace_detail where gid = {$info['group_id']} order by id desc limit {$this->pageSize} OFFSET {$offset} ";
            $traceDetail = yii::$app->db->createCommand($sql)->queryAll();
            Elog::logCrontab("\t".$sql."\n","analysisMailGroup_{$this->time}","info");
            if (empty($traceDetail)) {
                $msg =  "\t synUnsubscribe sql :" .$sql . " value inforamtion : " .\GuzzleHttp\json_encode($info) ."\n";
                Elog::logCrontab($msg,"analysisMailGroup_{$this->time}","info");
                break;
            }
//            self::updateMongodb($collection, ['email', 'email'], $traceDetail,[],false);
            self::updateMongodb(['email', 'email'], $traceDetail);
//            $orderInfo = null;
//            self::orderInfo($info, $orderInfo);
            ++$pageStart;
            $offset = $pageStart * $this->pageSize;
        }
        //邮箱退订
        //获取点击相关数据
        $table = "mail_group_unsubscribe_{$info['site_name']}";

        Elog::logCrontab("\t in the   synUnsubscribe method get  $table \n","analysisMailGroup_{$this->time}","info");
        self::initMongo();   //初始化mongo
        $collection = $this->mongodb->$table;
        $group_id = (string)$info['group_id'];
        $chickInfo = $collection->$table->find(
            ["group_id"=>"$group_id"],["group_id"=>1,"email"=>1,'_id' =>0]);
        $chickList = iterator_to_array($chickInfo);
        self::destroyMongo();

        foreach ($chickList as & $val) {
            $val['mailbox_unsubscribe'] = "1";
        }
//        self::updateMongodb($collection,['email','email'],$chickList,[],false);
        self::updateMongodb(['email','email'],$chickList);
        Elog::logCrontab("\t leave  synUnsubscribe method info \n","analysisMailGroup_{$this->time}","info");

    }

    /**
     * sendlist 同步到 MongoDB
     * $params data array [
     * group_id,
     * site_id
     * site_name
     * group_name...
     * ]
     */
    private function synSendEmail($info) {
        Elog::logCrontab("\t go in  synSendEmail method info" .\GuzzleHttp\json_encode($info) . "\n","analysisMailGroup_{$this->time}","info");
        $pageStart = 0;
        $offset = 0;
        $sendListModel = new MailSendlist();
        $sendListTable =$sendListModel->getTableName($info['site_id'], $info['group_id']);
        // 获取发送成功mail_sendlist_*.id区间条件
        $sendlistSucces = $sendListModel->getMailSubgroupCond("group_id = {$info['group_id']} and state = 2",$info['group_id'],"ms.id");
        if (empty($sendlistSucces)) {   //此分组没有发送成功数据
            return ;
        }

        $sql = " select count(*) as count from  {$sendListTable} as ms where $sendlistSucces";
        $count =  yii::$app->db->createCommand($sql)->queryAll();
        if (empty($count[0]['count'])) {
            return ;
        }
        $table = $this->table;
        self::initMongo();   //初始化mongo
        $collection = $this->mongodb->$table;
        $collection->createIndex(["user_id"=>1],["background"=>1]);   //创建索引
        $collection->createIndex(["email"=>1],["background"=>1]);   //创建索引
        self::destroyMongo();
        //获取分组上次执行的停止的信息，如果有的话
        $nextActionInfo = self::getAnalysisSchedule($info['group_id']); //['group_id' =>'grop_id','synSendEmail'=>['id'=>'值']];
        if (empty($sendListTable)) {
            Elog::logCrontab("\t go in  synSendEmail method,get sendListTable faile.info" .\GuzzleHttp\json_encode($info) . "\n","analysisMailGroup_{$this->time}","info");
            return ;
        }


        while(true) {
            if (isset($nextActionInfo['synSendEmail']['id']) && ! empty($nextActionInfo['synSendEmail']['id'])) {
                $sql = "select ms.id,ms.user_id,ms.email,ms.email_type,ua.send_email_count,ua.login_count,ua.open_email_count,ua.click_email_count,ua.order_count "
                        . " from  {$sendListTable} as ms left join user_{$info['site_name']}_accumulative_count as ua on ms.user_id = ua.user_id where
 {$sendlistSucces} and ms.id <= {$nextActionInfo['synSendEmail']['id']} and group_id = {$info['group_id']} 
 order by id desc limit {$this->pageSize} OFFSET {$offset} ";
            }else {
                $sql = "select ms.id,ms.user_id,ms.email,ms.email_type,ua.send_email_count,ua.login_count,ua.open_email_count,ua.click_email_count,ua.order_count "
                        . " from  {$sendListTable} as ms left join user_{$info['site_name']}_accumulative_count as ua on ms.user_id = ua.user_id 
 where  {$sendlistSucces}  and group_id = {$info['group_id']} order by id desc limit {$this->pageSize} OFFSET {$offset} ";

            }
            Elog::logCrontab("\t".$sql."\n","analysisMailGroup_{$this->time}","info");
            $sendList = yii::$app->db->createCommand($sql)->queryAll();
            if(empty($sendList)) {   //导入完毕
                $msg = "\t The synSendEmail method has been completed,sql is " .$sql . "  completion : \n";
                Elog::logCrontab($msg,"analysisMailGroup_{$this->time}","info");
                return ;
            }
            self::updateAnalysisSchedule($info['group_id'],['synSendEmail'=>['id'=>$sendList['0']['id']]]);    //更新数据插入进度
            self::insertMongodb(['user_id','user_id'],$sendList,['track_code' => $info['track_code'],'site_id' => $info['site_id']]);
            ++$pageStart;
            $offset = $pageStart * $this->pageSize;
            unset($sendList);
        }
        Elog::logCrontab("\t leave synSendEmail method \n","analysisMailGroup_{$this->time}","info");
//        self::delAnalysisSchedule();        //删除执行成功的分组
    }


    /**
     *  订单数据同步
     *  $info [
     * group_id,
     * site_id
     * site_name
     * group_name...
     * ]
     *
     * $res 返回结果
     */
    private function synOrder($info) {
        Elog::logCrontab("\t go in  synOrder method info" .\GuzzleHttp\json_encode($info) . "\n","analysisMailGroup_{$this->time}","info");

        if ($info['site_id'] == 12 ) {    // gearbest 网站订单分析
            self::synGearbestOrder($info);
        }else {
            //其他网站订单分析
            self::sysNoGearbestOrder($info);
        }
        Elog::logCrontab("\t leave synOrder method \n","analysisMailGroup_{$this->time}","info");
    }
    /*
     *  同步非gearbest 站的订单
     *  @params $info [
     * group_id,
     * site_id
     * site_name
     * group_name...
     * ]
     *  添加信息
     *  [
     *  'country_code' => '国家编码',
     *  'country' => '所属国家',
     *  'order_amount' => '订单金额',
     *  'pay_status' => '支付状态',
     *  'single_terminal' => '下单终端',
     *  'good_sn' => '商品SKU',
     *  'category_id' => '最小分类ID'
     * ]
     *
     */

    private function sysNoGearbestOrder($info) {
        $pageStart = 0;
        $offset = 0;
        Elog::logCrontab("\t go in  sysNoGearbestOrder method info" .\GuzzleHttp\json_encode($info) . "\n","analysisMailGroup_{$this->time}","info");
        //获取国家对应国家编码表
        $sql = "select region_id,region_code as country_code,region_name as country from region";
        $regionList = yii::$app->db->createCommand($sql)->queryAll();
        Elog::logCrontab("\t go in  sysNoGearbestOrder method get region table " .\GuzzleHttp\json_encode($sql) . "\n","analysisMailGroup_{$this->time}","info");
        $regionList = self::arrKeyToIndex($regionList,'region_id');

        while(true) {
            $sql = "select order_sn,terminal as single_terminal from 
vw_order_mail_info where group_id = '{$info['group_id']}' order by id desc limit {$this->updateOrderSize} OFFSET {$offset} ";
            $mailList = yii::$app->db->createCommand($sql)->queryAll();
            Elog::logCrontab("\t".$sql."\n","analysisMailGroup_{$this->time}","info");
            if (empty($mailList)) {
                $msg = "\t" . "in the sysNoGearbestOrder method\t" . \GuzzleHttp\json_encode($info) ."sysNoGearbestOrder sql :" .$sql . " value inforamtion : " .\GuzzleHttp\json_encode($info)."\n";
                Elog::logCrontab($msg,"analysisMailGroup_{$this->time}","info");
                return ;
            }
            ++$pageStart;
            $offset = $pageStart * $this->updateOrderSize;
            $order_sn_str = self::arr2str($mailList,'order_sn','string');

            //获取订单信息
            $sql = "select user_id,order_sn,order_id,order_amount,order_status as pay_status,country as region_id from 
tb_eload_order_info where  order_sn in($order_sn_str)";

            $orderList = yii::$app->db->createCommand($sql)->queryAll();
            Elog::logCrontab("\t".$sql."\n","analysisMailGroup_{$this->time}","info");
            if( empty($orderList) ) {  // 因为只有订单有user_id ,如果订单为空，直接跳过
                $msg = "\t The synSendEmail method has been completed,sql is. {$sql} \n";
                Elog::logCrontab($msg,"analysisMailGroup_{$this->time}","info");
                return ;
            }
            // 添加国家名 country,和国家编码country_code
            $orderList = self::accorKeyMergeArray($orderList,$regionList,'region_id');

            $siteUserIdArr = []; // 网站用户id数组
            foreach ($orderList as $orderListVal) {
                if (!in_array($orderListVal['user_id'],$siteUserIdArr)) {
                    $siteUserIdArr[] = $orderListVal['user_id'];
                }

            }
            $userIdArr = [];
            $userIdArrDeal = [];
            if ($siteUserIdArr) {
                $siteUserIdStr = join(',',$siteUserIdArr);
                $sqlGetUserId = "select user_id,site_user_id from user_{$info['site_name']} where site_user_id in ({$siteUserIdStr})";
                $userIdArr = yii::$app->db->createCommand($sqlGetUserId)->queryAll();

                foreach ($userIdArr as $userIdArrVal) {
                    $userIdArrDeal[$userIdArrVal['site_user_id']] = $userIdArrVal['user_id'];
                }
            }

            foreach ($orderList  as $key=>$orderListVal) {
                if (!empty($userIdArrDeal[$orderListVal['user_id']])) {
                    $orderList[$key]['user_id'] = $userIdArrDeal[$orderListVal['user_id']];
                }
            }

            $order_id_str = self::arr2str($orderList,'order_id');
            //获取商品信息
            //$sql = "select goods_sn,cat_id as category_id,order_id from tb_eload_order_goods where  order_id in({$order_id_str})";
            $sql = "select go.goods_sn,go.cat_id as category_id,go.order_id,gc.cat_name as category_name,go.goods_name as goods_name,go.goods_number as goods_number from tb_eload_order_goods as go left join "
                    . " cloth_category_data as gc on go.cat_id=gc.cat_id and go.data_from=gc.data_from where  go.order_id in({$order_id_str})";
            $orderGoodList = yii::$app->db->createCommand($sql)->queryAll();
            Elog::logCrontab("\t $sql \n","analysisMailGroup_{$this->time}","info");
            $mailList = self::arrKeyToIndex($mailList,'order_sn');
            $orderList = self::accorKeyMergeArray($orderList,$mailList,'order_sn');
            self::gearbestOrderDiviceTypeReset($orderList,'otherOrderDeviceType');     //重置设备类型

            if ( empty($orderGoodList)) {  //如果商品信息为空，直接同步订单信息
//                self::updateOrderMongodb($collection,['user_id','user_id'],$orderList,
//                    ['key' => "have_order_record","val"=>"1"],true,false);
                self::orderCombinationUpdate(['user_id','user_id'],$orderList,
                    ['key' => "have_order_record","val"=>"1"],true);
            }
            $orderList = self::arrKeyToIndex($orderList,'order_id');
            $orderGoodList = self::accorKeyMergeArray($orderGoodList,$orderList,'order_id');
            //['have_order_record' => "1"] 代表有下过订单
//            self::updateOrderMongodb($collection,['user_id','user_id'],$orderGoodList,
//                ['key' => "have_order_record","val"=>"1"],true,false);
            self::orderCombinationUpdate(['user_id','user_id'],$orderGoodList,
                ['key' => "have_order_record","val"=>"1"],true);
            unset($mailList,$order_sn_str,$orderList,$order_id_str,$orderGoodList);
        }
        Elog::logCrontab("\t leave sysNoGearbestOrder method \n","analysisMailGroup_{$this->time}","info");

    }

    /**
     *  gearbest 订单设备类型重置
     *  $orderList 订单数据列表
     *  $type 订单类型
     */
    private function gearbestOrderDiviceTypeReset(& $orderList,$type ='gearbestOrderDeviceType') {
        if ( ! is_array($orderList)) {
            return;
        }
        $divice = null;
        switch ($type) {
            case 'gearbestOrderDeviceType':
                $divice = $this->gearbestOrderDeviceType;
                break;
            case 'otherOrderDeviceType':
                $divice = $this->otherOrderDeviceType;
                break;
            default :
                Elog::logCrontab("\t in the  gearbestOrderDiviceTypeReset method ,The order type cannot be identified \n","analysisMailGroup_{$this->time}","info");
                return;
        }
        foreach ($orderList as & $val ) {
            if ( ! isset($divice[$val['single_terminal']])) {  //不存在则赋值other
                $val['single_terminal'] = $divice['0'];
                continue;
            }
            $val['single_terminal'] = $divice[$val['single_terminal']];
        }
    }

    /**
     * gearbest 订单
     * 添加信息
     * [
     *  'country_code' => '国家编码',
     *  'country' => '所属国家',
     *  'order_amount' => '订单金额',
     *  'pay_status' => '支付状态',
     *  'single_terminal' => '下单终端',
     *  'good_sn' => '商品SKU',
     *  'category_id' => '最小分类ID'
     * ]
     */
    private function synGearbestOrder($info) {
        Elog::logCrontab("\t go in  synGearbestOrder method info\t" .\GuzzleHttp\json_encode($info) . "\n","analysisMailGroup_{$this->time}","info");

        $pageStart = 0;
        $offset = 0;
        parse_str($info['track_code'],$track_info);
        if ( ! isset($track_info['utm_campaign']) ) {
            return ;
        }
        $track_code = $track_info['utm_campaign'];

        while(true) {
//            $sql = "select user_id,utm_campaign as track_code,pay_status,order_amount,country,country_code,order_sn,platform single_terminal from
//gearbest_order_market_data where utm_campaign = '$track_code' order by id desc limit  {$this->updateOrderSize} OFFSET {$offset} ";
            $sql = "select user_id,utm_campaign as track_code,pay_status,order_amount,country,country_code,order_sn,platform single_terminal from 
gearbest_order_market_data where utm_campaign like '$track_code%' order by id desc limit  {$this->updateOrderSize} OFFSET {$offset} ";
            $orderInfo = yii::$app->db->createCommand($sql)->queryAll();
            Elog::logCrontab("\t".$sql."\n","analysisMailGroup_{$this->time}","info");
            if(empty($orderInfo)) {   //导入完毕
                $msg = "\t The synGearbestOrder method has been completed,sql is  sql : {$sql}"  ;
                Elog::logCrontab($msg,"analysisMailGroup_{$this->time}","info");
                return ;
            }

            $siteUserIdArr = []; // 网站用户id数组
            foreach ($orderInfo as $orderListVal) {
                if (!in_array($orderListVal['user_id'],$siteUserIdArr)) {
                    $siteUserIdArr[] = $orderListVal['user_id'];
                }

            }
            $userIdArr = [];
            $userIdArrDeal = [];
            if ($siteUserIdArr) {
                $siteUserIdStr = join(',',$siteUserIdArr);
                $sqlGetUserId = "select user_id,site_user_id from user_{$info['site_name']} where site_user_id in ({$siteUserIdStr})";
                $userIdArr = yii::$app->db->createCommand($sqlGetUserId)->queryAll();

                foreach ($userIdArr as $userIdArrVal) {
                    $userIdArrDeal[$userIdArrVal['site_user_id']] = $userIdArrVal['user_id'];
                }
            }
            foreach ($orderInfo  as $key=>$orderListVal) {
                if (!empty($userIdArrDeal[$orderListVal['user_id']])) {
                    $orderInfo[$key]['user_id'] = $userIdArrDeal[$orderListVal['user_id']];
                }
            }

            //商品信息同步
            $order_sn_str = $this->arr2str($orderInfo,'order_sn','string');
           // $goodSql = "select goods_sn,order_sn,category_id from gearbest_order_goods_data where order_sn in({$order_sn_str})";
            $goodSql = "select go.goods_sn,go.order_sn,go.category_id,gc.category_name,go.goods_name as goods_name,go.qty as goods_number from"
                    . " gearbest_order_goods_data as go left join gearbest_category_data gc on go.category_id=gc.category_id  where go.order_sn in({$order_sn_str})";
            $goodInfo = yii::$app->db->createCommand($goodSql)->queryAll();
            Elog::logCrontab("\t".$goodSql."\n","analysisMailGroup_{$this->time}","info");
            ++$pageStart;
            $offset = $pageStart * $this->updateOrderSize;
            self::gearbestOrderDiviceTypeReset($orderInfo,'gearbestOrderDeviceType');     //重置设备类型

            if (empty($goodInfo)) {   //没有商品，直接添加订单信息
//                self::updateOrderMongodb($collection,['user_id','user_id'],$orderInfo,
//                    ['key' => "have_order_record","val"=>"1"],true,false);
                self::orderCombinationUpdate(['user_id','user_id'],$orderInfo,
                    ['key' => "have_order_record","val"=>"1"],true);
            }
            $goodInfo = self::getGearbestFirstCategory($goodInfo);   //获取一级品类
            //订单信息和商品信息组合添加
//            $goodInfo = self::arrKeyToIndex($goodInfo,'order_sn');
//            $orderInfo = self::accorKeyMergeArray($orderInfo,$goodInfo,'order_sn');

            $orderInfo = self::arrKeyToIndex($orderInfo,'order_sn');
            $orderInfo = self::accorKeyMergeArray($goodInfo,$orderInfo,'order_sn');
//            self::updateOrderMongodb($collection,['user_id','user_id'],$orderInfo,
//                ['key' => "have_order_record","val"=>"1"],true,false);
            self::orderCombinationUpdate(['user_id','user_id'],$orderInfo,
                ['key' => "have_order_record","val"=>"1"],true);
            unset($orderInfo,$goodInfo,$goodSql,$sql);
        }
        return ;
    }


    /*
     * 获取gearbest的一级评论
     * 可以调优： 数据同步是把品类信息存储在数组里
     *
     */
    private function getGearbestFirstCategory( $goodInfo) {
        foreach ($goodInfo as & $val ) {

            if (empty($val['category_id'])) {
                continue;
            }
            $sql = "select * from gearbest_category_data where category_id = {$val['category_id']}";
            $categoryInfo = yii::$app->db->createCommand($sql)->queryOne();

            if (empty($categoryInfo) || empty($categoryInfo['is_leaves'])) {
                continue;
            }
            $category_str =trim($categoryInfo['min_category_relation'],',');

            $category_arr = explode(",",$category_str);
            if ( ! isset($category_arr[0]) || empty($category_arr[0]) ) {
                continue;
            }
            $sql = "select * from gearbest_category_data where category_id = {$category_arr[0]}";
            $categoryInfo = yii::$app->db->createCommand($sql)->queryOne();

            if (empty($categoryInfo) || ! isset($categoryInfo['category_id'],$categoryInfo['category_name'])) {
                continue;
            }
            $val['category_id'] = $categoryInfo['category_id'];
            $val['category_name'] = $categoryInfo['category_name'];
        }
        return $goodInfo;
    }



    /**
     * @parmas info array [
     * group_id,
     * site_id
     * site_name
     * group_name...
     * ]
     *  点击数据和设备同步
     *  //db.open_report_record_gearbest.find({'group_id':99},{group_id: 1, open_teminal: 1,user_id:1,open_count:1})
     */
    private function synChick($info) {
        $pageStart = 0;
        $offset = 0;
        $table = "email_{$info['site_name']}_open_data";  //email_zaful_open_data
        while(true) {
            $sql = "select group_id,user_id,open_teminal,email_type,count(user_id) as open_count from $table where  group_id= {$info['group_id']} group by user_id order by id desc limit {$this->pageSize} OFFSET {$offset} ";
            Elog::logCrontab("\t".$sql."\n","analysisMailGroup_{$this->time}","info");
            $chickList = yii::$app->db->createCommand($sql)->queryAll();
            if(empty($chickList)) {   //导入完毕
                $msg = "\t The synChick method has been completed,sql is " .$sql . "  completion : \n";
                Elog::logCrontab($msg,"analysisMailGroup_{$this->time}","info");
                return ;
            }
            foreach ($chickList as &$val) {  //强制转化类型。保持类型一致性
                $val['open_count'] = (int)$val['open_count'];
            }

            self::updateMongodb(['user_id','user_id'],$chickList);
            ++$pageStart;
            $offset = $pageStart * $this->pageSize;
        }
        Elog::logCrontab("\t leave  synChick method info \n","analysisMailGroup_{$this->time}","info");
    }

    /***
     * 从多维数组或对象数组中构建一个映射
     * 根据$array 指定$array[$key]为key 名
     * For example,
     * $array = [
     *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
     *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
     *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
     * ];
     *
     * $result = self::arrKeyToIndex($array, 'name');
     * // the result is:
     * // [
     * //     'aaa' => ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
     * //     'bbb' => ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
     * //     'ccc' => ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
     * // ]
     *
     */
    private function arrKeyToIndex($array,$key) {
        if (empty($array) || empty($key)) {
            return false;
        }
        $res = [];
        foreach ( $array as $item) {
            if ( isset($item[$key])) {
                $res[$item[$key]] = $item;
            }
        }
        return $res;
    }

    /**
     *  从多维数组或对象中，如果$array[$key] 值存在 array_key 的下标中，则组合数组
     * For example,
     *  $arr = [
     *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
     *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
     *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
     *  ];
     *
     * $arr_2 = [
     *    'aaa' => [ 'gender' => 'female', 'weight' => 60],
     *    'bbb' => [ 'gender' => 'female', 'weight' => 50],
     *    'ccc' => [ 'gender' => 'male', 'weight' => 55],
     * ]
     *
     *
     * $result = self::accorKeyMergeArray($arr,$arr_2,'name');
     * // the result is:
     * // [
     * //     'aaa' => ['id' => '123', 'name' => 'aaa', 'class' => 'x','gender' => 'female', 'weight' => 60],
     * //     'bbb' => ['id' => '124', 'name' => 'bbb', 'class' => 'x','gender' => 'female', 'weight' => 50],
     * //     'ccc' => ['id' => '345', 'name' => 'ccc', 'class' => 'y','gender' => 'male', 'weight' => 55],
     * // ]
     *
     *
     */

    private function accorKeyMergeArray($arr,$arr_2,$arrIndex)
    {
        if(empty($arr) || empty($arrIndex)) {
            return false;
        }
        foreach ($arr as & $item) {
            $key = $item[$arrIndex];
            if (isset($arr_2[$key])) {
                $item = array_merge($item,$arr_2[$key]);
            }
        }
        return $arr;
    }



    /**
     * 返回二维数组，指定下标，值非空的$delimiter分隔字符串,$delimiter 默认为逗号
     * 返回逗号分隔字符串
     *
     */
    private function arr2str($array,$key,$type ='int',$delimiter = ',') {
        if (empty($array) || empty($key)) {
            return false;
        }
        $string = '';
        if ($type =='int') {
            foreach($array as $val) {
                if( isset($val[$key]) && ! empty($val[$key])) {
                    $string .= $val[$key] .$delimiter;
                }
            }
        } else {
            foreach($array as $val) {
                if( isset($val[$key]) && ! empty($val[$key])) {
                    $string .= "'{$val[$key]}'$delimiter";
                }
            }
        }
        return rtrim($string,$delimiter);
    }

    /**
     * 邮件退订数据(mail_trace_detail)
     * $cond [0 => 'key' ,1 =>'对应$update中的key']
     */
    private function updateMongodb($cond,$update,$add=[],$upsert=true) {
        if (empty($cond) || empty($update)) {
            return false;
        }

        $databaseName = trim(strrchr($this->mongodsn,"/"),"/");   //获取配置信息中，/后面的库名
//        $manager = new \MongoDB\Driver\Manager($this->mongodsn);
        Elog::logCrontab("\t in to updateMongodb ,table from $this->table \n","analysisMailGroup_{$this->time}","info");
        $updates = [];
        $i = 0;

        foreach ( $update as $val) {
            if (!empty($add)) {
                $val += $add;
            }
            if (!isset($val[$cond[1]])) {
                continue;
            }
            $updates[] = [
                "q" => [$cond[0] => $val[$cond[1]]],
                "u" => ['$set' => $val],
                'upsert' => $upsert
            ];
            ++$i;
            if ( $i % $this->batchSize == 0) {
                $manager = new \MongoDB\Driver\Manager($this->mongodsn);
                $start = (intval($i / $this->batchSize)) * $this->batchSize - $this->batchSize;
                Elog::logCrontab("The updateMongodb method, $this->table aggregation ready to update the data of the $start~ $i interval", "analysisMailGroup_{$this->time}", "info");
                $cmd = ['update' => $this->table, 'updates' => $updates,'maxTimeMS'=>120000];
                $command = new \MongoDB\Driver\Command($cmd);
                try {
                    $manager->executeCommand($databaseName, $command);
                } catch (\MongoDB\Driver\Exception $e) {
                    $msg = "in the updateMongodb function,$this->table aggregation update failed\t " . "update condition " . \GuzzleHttp\json_encode($cmd) . "catch information " . $e->getMessage();
                    Elog::logCrontab($msg, "analysisMailGroup_{$this->time}", "info");
                    throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
                }
                $updates = null;  //重置为空
                Elog::logCrontab("in the updateMongodb method \t, $start~ $i data update completion", "analysisMailGroup_{$this->time}", "info");
            }
        }

        if ( $i % $this->batchSize !=0 ) {
            $start = (intval($i / $this->batchSize)) * $this->batchSize  - $this->batchSize;
            Elog::logCrontab("The updateMongodb method, $this->table aggregation ready to update the data of the $start~ $i interval", "analysisMailGroup_{$this->time}", "info");
            $cmd = ['update' => $this->table, 'updates' => $updates,'maxTimeMS'=>120000];
            $manager = new \MongoDB\Driver\Manager($this->mongodsn);
            $command = new \MongoDB\Driver\Command($cmd);
            try {
                $manager->executeCommand($databaseName, $command);
            } catch (\MongoDB\Driver\Exception $e) {
                $msg = "in the updateMongodb function,$this->table aggregation update failed\t " . "update condition " . \GuzzleHttp\json_encode($cmd) . "catch information " . $e->getMessage();
                Elog::logCrontab($msg, "analysisMailGroup_{$this->time}", "info");
                throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
            }
            Elog::logCrontab("in the updateMongodb method \t, $this->table aggregation, $start~ $i data update completion", "analysisMailGroup_{$this->time}", "info");
        }
        Elog::logCrontab("$this->table aggregation, leave updateMongodb function  \n","analysisMailGroup_{$this->time}","info");
    }

    /**
     * 邮件退订数据(mail_trace_detail)
     * $cond [0 => 'key' ,1 =>'对应$update中的key']
     */
    private function insertMongodb($cond,$update,$add=[],$upsert=true) {
        if ( empty($cond) || empty($update)) {
            return false;
        }
        Elog::logCrontab("in to insertMongodb function  \n","analysisMailGroup_{$this->time}","info");
        $databaseName = trim(strrchr($this->mongodsn,"/"),"/");   //获取配置信息中，/后面的库名
        $manager = new \MongoDB\Driver\Manager($this->mongodsn);
        Elog::logCrontab("\t in to insertMongodb ,table from $this->table \n","analysisMailGroup_{$this->time}","info");
        $bulk = new \MongoDB\Driver\BulkWrite;
        foreach ( $update as $val) {
            $bulk->insert($val);
        }
        try {
            $manager->executeBulkWrite("$databaseName.$this->table", $bulk);
        } catch(\MongoDB\Driver\Exception $e) {
            $msg = "in the insertMongodb function,insert failed" ."update condition " . \GuzzleHttp\json_encode($bulk) . "catch information " .$e->getMessage() ;
            Elog::logCrontab($msg,"analysisMailGroup_{$this->time}","info");
            throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
        }
        Elog::logCrontab(" $this->table aggregation,leave insertMongodb function  \n","analysisMailGroup_{$this->time}","info");
    }


    /**
     *  订单数据插入
     *  $outerlayer:false 非外层['key'=>'value']，true,外面一层['key'=>'index','index'=>$val]
     */
    private function updateOrderMongodb($cond,$update,$add=[],$outerLayer=false,$upsert=true) {
        if ( empty($cond) || empty($update)) {
            return false;
        }
        $databaseName = trim(strrchr($this->mongodsn,"/"),"/");   //获取配置信息中，/后面的库名
//        $manager = new \MongoDB\Driver\Manager($this->mongodsn);
        $updates = [];
        $i = 0;
        Elog::logCrontab("\t go in updateOrderMongodb ,table from $this->table \n","analysisMailGroup_{$this->time}","info");
        foreach ( $update as $val) {

            if (isset($val['order_amount'])) {
                $val['order_amount'] = (float)$val['order_amount'];
            }

            if (isset($val['order_amount'])) {
                $val['single_terminal'] = (float)$val['single_terminal'];
            }
            if (!isset($val[$cond[1]])) {
                continue;
            }

            if ( ! empty($add)) {
                if (empty($outerLayer)) {
                    $val += $add;
                    $updates[] = [
                        "q" => [$cond[0] => $val[$cond[1]], ],
                        "u" => ['$set' => ['orders' => $val]],   //同一个json 层
                        'upsert' => $upsert
                    ];
                }else {
                    $updates[] = [
                        "q" => [$cond[0] => $val[$cond[1]]],
                        "u" => ['$set' => ['orders' => $val,$add['key'] =>$add['val']]],
                        'upsert' => $upsert
                    ];
                }
            } else {
                $updates[] = [
                    "q" => [$cond[0] => $val[$cond[1]]],
                    "u" => ['$set' => ['orders' => $val]],
                    'upsert' => $upsert
                ];
            }
            ++$i;
            if ( $i % $this->batchSize == 0) {
                $start = (intval($i / $this->batchSize)) * $this->batchSize  - $this->batchSize;
                Elog::logCrontab("The updateOrderMongodb method,$this->table aggregation  ready to update the data of the $start~ $i interval", "analysisMailGroup_{$this->time}", "info");
                $cmd = ['update' => $this->table,'updates' => $updates,'maxTimeMS'=>120000];
                $manager = new \MongoDB\Driver\Manager($this->mongodsn);

                $command = new \MongoDB\Driver\Command($cmd);
                try {
                    $manager->executeCommand($databaseName, $command);
                } catch(\MongoDB\Driver\Exception $e) {
                    $msg = "in the updateOrderMongodb method ,update failed \t" ."update condition " . \GuzzleHttp\json_encode($cmd) . "catch information " .$e->getMessage();
                    Elog::logCrontab($msg,"analysisMailGroup_{$this->time}","info");
                    throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
                }
                $updates = null;  //重置为空
                Elog::logCrontab("in the updateOrderMongodb method ,$this->table aggregation update completion", "analysisMailGroup_{$this->time}", "info");
            }
        }

        if ( $i % $this->batchSize !=0 ) {
            $start = (intval($i / $this->batchSize)) * $this->batchSize  - $this->batchSize;
            Elog::logCrontab("The updateOrderMongodb method,$this->table aggregation ready to update the data of the $start~ $i interval", "analysisMailGroup_{$this->time}", "info");
            $cmd = ['update' => $this->table, 'updates' => $updates,'maxTimeMS'=>120000];
            $manager = new \MongoDB\Driver\Manager($this->mongodsn);
            $command = new \MongoDB\Driver\Command($cmd);
            try {
                $manager->executeCommand($databaseName, $command);
            } catch (\MongoDB\Driver\Exception $e) {
                $msg = "in the updateOrderMongodb method ,$this->table aggregation update failed \t" ."update condition " . \GuzzleHttp\json_encode($cmd) . "catch information " .$e->getMessage();
                Elog::logCrontab($msg, "analysisMailGroup_{$this->time}", "info");
            }
            Elog::logCrontab("in the updateOrderMongodb method ,update completion", "analysisMailGroup_{$this->time}", "info");
        }
        Elog::logCrontab("\t $this->table aggregation,leave updateMongodb function  \n","analysisMailGroup_{$this->time}","info");
    }

    /**
     *  处理一个订单多个good_sn覆盖情况
     *
     */

    public function orderCombinationUpdate($cond,$update,$add=[],$outerLayer=false,$upsert=true) {
        Elog::logCrontab("go in orderCombinationUpdate method:update".\GuzzleHttp\json_encode($update), "analysisMailGroup_{$this->time}", "info");
        self::initMongo();
        $table = $this->table;
        $db = $this->mongodb->$table;
        if (empty($cond) || empty($update)) {
            return false;
        }
        foreach ( $update as $val) {
            if (isset($val['order_amount'])) {
                $val['order_amount'] = (float)$val['order_amount'];
            }

            if (isset($val['order_amount'])) {
                $val['single_terminal'] = (float)$val['single_terminal'];
            }
            if (! isset($val[$cond[1]],$val['goods_sn'],$val['order_sn'])) {
                continue;
            }
            //查找，存在时更新，不存在时插入
            if ( ! empty($add)) {
                $res = $db->update([$cond[0] => $val[$cond[1]],'orders'=>['$elemMatch'=>['goods_sn'=>$val['goods_sn'],'order_sn'=>$val['order_sn']]]],
                    ['$set' =>['orders.$' => $val,$add['key'] => $add['val']]                             // 更新内容
                    ]);
            }else {
                $res = $db->update([$cond[0] => $val[$cond[1]],'orders'=>['$elemMatch'=>['goods_sn'=>$val['goods_sn'],'order_sn'=>$val['order_sn']]]],
                    ['$set' =>['orders.$' => $val]]
                );
            }
            if (  ! empty($res['updatedExisting'])) {           //如果数据不存在则添加
                continue;
            }
            //不存在则添加
            if ( !empty($add)) {
                $db->update([$cond[0] => $val[$cond[1]]],
                    ['$set' =>[$add['key'] => $add['val']],'$push'=>['orders'=>(array)($val)]]);

            }else {
                $db->update([$cond[0] => $val[$cond[1]]],
                    ['$push'=>['orders'=>$val]]);
            }

        }
        self::destroyMongo();
        Elog::logCrontab("leave orderCombinationUpdate method ,update completion", "analysisMailGroup_{$this->time}", "info");


    }



    public function actionTotalTransformation() {
        $post = $_REQUEST;
        if (empty($post['group_id'])) {
            $this->error('group_id 不能为空');
        }
        self::initMongo();
        $m =  $this->mongodb;
        $table = $this->res_backup;
        $collection  =$m->$table;
        $exist = $collection->find(['group_id'=>$post['group_id']],['_id'=>0,'group_id'=>0]);
        self::destroyMongo();
        $res = iterator_to_array($exist);
        if (empty($res)) {
            $totalTransformation = self::totalTransformation(['group_id'=>$post['group_id']]);
        } else {
            $totalTransformation = $res[0];
        }
        $this->success($totalTransformation);
    }
    /**
     *
     * 订单转化
     * 订单总额
     * 付款总额
     * 订单数
     * 付款订单数
     * 付款金额率
     * 付款订单率
     *
     */
    public  function totalTransformation($info)
    {  // $post['group_id'] = 15571;
//        $post = Yii::$app->request->post();
        if (empty($info['group_id'])) {
            return false;
        }
        $group_id = $info['group_id'];
        $totalTrans= [                 // 邮件转化分析
            'order_amount' => 0,                // 订单总额
            'pay_order_amount' => 0,            // 付款总额 ,note :汇总统计该发送分组的已支付订单总金额, 币种为美元（$）。
            'order_num' => 0,                   // 订单数,note : 汇总统计该发送分组的所有订单数（单位：个），按订单号汇总
            'pay_order_num' => 0,               // 付款订单数 ,note : 汇总统计该发送分组的所有已支付订单数（单位：个），按订单号汇总。
            'pay_amount_rate' => 0,             // 付款金额率 ,note : 付款金额率=[付款总额/订单总额]*100%
            'pay_order_rate' => 0,              // 付款订单率 ,note : 付款订单率=[付款订单数/订单数] *100%
            'send_email_num' => 0,           // 邮件发送数量
            'send_email_success_num' => 0,   // 邮件发送成功的数量, note : 渠道返回的该发送分组发送成功用户数。
            'email_success_rate' => 0,          // 邮件发送成功率 , note :  渠道返回的该发送分组发送成功用户数。
            'email_open_num' => 0,           // 邮件打开的数量 , note : 取该发送分组的独立打开用户数
            'email_open_rate' => 0,             // 邮件打开率 , note : 打开率=[独立打开用户数/发送成功] *100%
            'user_click_num' => 0,           // 用户点击邮件数量（用户点击）, note : 取该发送分组的独立点击用户数
            'user_click_rate' => 0,             // 用户点击邮件率（用户点击率）, note : 点击转化率=[独立点击用户数/独立打开用户数] *100%
            'single_user_num' => 0,     // 下单用户数 (汇总统计该发送分组的下单用户数（按网站用户ID汇总）)
            'single_user_rate' => 0,    // 下单用户率 (用户下单率=[下单用户数/独立点击用户数] *100%)
            'pay_user_num' => 0,        // 付费用户数(用户付款) ,note :汇总统计该发送分组的下过订单并且已支付的用户数（按网站用户ID汇总）
            'pay_user_rate' => 0,       // 付费用户率 note : 用户付款率=[用户付款 /用户下单] *100%
            'bounces_num' => 0,         // 弹回数 note: 弹回总数=硬弹用户数+软弹用户数
            'bounces_rate' => 0,        // 弹回率 note: 弹回率=[弹回总数/发送总量]*100%
            'hard_bounces_num' => 0,    // 硬弹数
            'hard_bounces_rate' => 0,   // 硬弹率 note: 硬弹率=[硬弹用户数/弹回总数]*100%
            'soft_bounces_num' => 0,    // 软弹数
            'soft_bounces_rate' => 0,   // 软弹率 note: 软弹率=[硬弹用户数/弹回总数]*100%
            'complaint_num' => 0,       // 投诉数
            'complaint_rate' => 0,      // 投诉率 note: 投诉率=[投诉用户数/发送成功数] *100%
            'unsubscribe_num' => 0,     // 退订数
            'unsubscribe_rate' => 0,    // 退订率 note: 投诉率=[投诉用户数/发送成功数] *100%
            'mailbox_unsubscribe_num' =>0, // 邮箱退订数
            'mail_unsubscribe_num' => 0,   //邮件退订数
            'mailbox_unsubscribe_rate' => 0, //  邮箱退订率
            'mail_unsubscribe_rate' => 0,    // 邮件退订率
        ];
        self::initMongo();
        $table = $this->prefix.$group_id;
        $db =  $this->mongodb->$table;
        /*
        //订单总额和订单数
        $orderInfo = $db->aggregate([
            ['$unwind'=>'$orders'],
            ['$group' =>[
                '_id' =>"",
                'order_amount' => ['$sum' => '$orders.order_amount'],
                'order_num' => ['$sum' =>1]             //order_num(订单数)
            ]]]);

        if (! empty($orderInfo['result'])) {
            $totalTrans['order_amount'] = $orderInfo['result'][0]['order_amount'];
            $totalTrans['order_num'] = $orderInfo['result'][0]['order_num'];
        }

        //付款总额和付款订单数
        $orderInfo = $db->aggregate([
            ['$unwind'=>'$orders'],
            ['$match'=>['orders.pay_status'=>['$gte'=>"1"]]],
            ['$group'=>['_id'=>'',
                'pay_order_num' =>['$sum' =>1],
                'pay_order_amount'=>['$sum'=>'$orders.order_amount'],
            ]]
        ]);
        if (! empty($orderInfo['result'])) {
            $totalTrans['pay_order_amount'] = $orderInfo['result'][0]['pay_order_amount'];
            $totalTrans['pay_order_num'] = $orderInfo['result'][0]['pay_order_num'];
        }

        //$totalTrans['pay_user_num'] = $db->find(['pay_status'=> ['$gte'=>"1"]])->count();
        $orderInfo = $db->aggregate([
            ['$unwind'=>'$orders'],
            ['$match'=>['orders.pay_status'=>['$gte'=>"1"]]],
            ['$group'=>['_id'=>'$user_id'
            ]]
        ]);
        // 付费用户数
        if (! empty($orderInfo['result'])) {
            $totalTrans['pay_user_num'] = count($orderInfo['result']);
        }

        $orderInfo = $db->aggregate([
            ['$match'=>['orders.order_id'=>['$ne'=>null]]],
            ['$group'=>['_id'=>'$user_id']]
        ]);
        //下单用户数
        if (! empty($orderInfo['result'])) {
            $totalTrans['single_user_num'] = count($orderInfo['result']);
        }
        */
        $orderList = $db->find(["orders"=>['$exists'=>"true"]],['orders'=>1,'_id'=>0]);
        $orderList = iterator_to_array($orderList);
        $orderArr = [];
        $singleUserArr = [];
        foreach ($orderList as $val) {
            if (!is_array($val['orders'])) {
                continue;
            }
            foreach ($val['orders'] as $v) {
                if ( ! isset($orderArr[$v['order_sn']])) {
                    ++$totalTrans['order_num'];
                    $totalTrans['order_amount'] += isset($v['order_amount']) ? $v['order_amount']: 0;
                    if ($v['pay_status']>= 1) {
                        ++$totalTrans['pay_order_num'];
                        ++$totalTrans['pay_user_num'];
                        $totalTrans['pay_order_amount'] += isset($v['order_amount']) ? $v['order_amount'] : 0;
                    }
                    $orderArr[$v['order_sn']] = $v['order_sn'];
                    $singleUserArr[$v['user_id']] = $v['user_id'];
                }
            }
        }
        $totalTrans['single_user_num'] = count($singleUserArr);
        /*
        rder_num(订单数),
        pay_order_num(付款订单数),
        send_email_success_num(邮件发送成功的数量),
        email_open_num(邮件打开的数量),
        user_click_num(用户点击邮件数量)
        single_user_num(下单用户数),   note: 要统计have_order_record，
        pay_user_num(付费用户数),
        bounces_num(弹回数),
        soft_bounces_num(软弹数)
        hard_bounces_num(硬弹数),
        complaint_num(投诉数),
        unsubscribe_num(退订数)
        */
        /*
         * [
             {$unwind:'$orders'},
             {$match:{'orders.pay_status':'1'}},
             {$group:{
                      _id:null,
                      count:{$sum:1}
                    }
             }
         ]
         */

//        $totalTrans['send_email_num'] = $db->find(['user_id'=>['$ne'=>null]])->count();
//        $totalTrans['send_email_success_num'] = $db->find(['$or' =>[['is_hard_bounces'=>"0"],['is_soft_bounces' =>"0"]]])->count();
        $totalTrans['send_email_num'] = self::getmailGroupSendCount($group_id);         // 发送总量
//        $totalTrans['send_email_success_num'] = $this->send_email_success_num;  //发送成功的数量
        $totalTrans['email_open_num'] = $db->find(['open_count'=> ['$gte'=>1]])->count();
        $totalTrans['user_click_num'] = $db->find(['is_click'=> "1"])->count();
        $totalTrans['single_user_num'] = $db->find(['have_order_record'=> "1"])->count();
        $totalTrans['soft_bounces_num'] = $db->find(['is_soft_bounces'=> "1"])->count();
        $totalTrans['hard_bounces_num'] = $db->find(['is_hard_bounces'=> "1"])->count();
        $totalTrans['complaint_num'] = $db->find(['is_complaint'=> ['$gte'=>"1"]])->count();
        $totalTrans['mail_unsubscribe_num'] = $db->find(['is_unsubscribe'=> ['$gte'=>"1"]])->count();
//        $totalTrans['mailbox_unsubscribe_num'] = $db->find(['mailbox_unsubscribe'=> ['$gte'=>1]])->count();
        $totalTrans['mailbox_unsubscribe_num'] = $db->find(['mailbox_unsubscribe'=> '1'])->count();
        $totalTrans['unsubscribe_num'] = $totalTrans['mail_unsubscribe_num'] + $totalTrans['mailbox_unsubscribe_num'];   //退订总量
        $totalTrans['send_email_success_num'] =  $totalTrans['send_email_num'] -  $totalTrans['soft_bounces_num'] - $totalTrans['hard_bounces_num'] ;
        /*
         * pay_amount_rate 付款金额率
         * pay_order_rate 付款订单率
         * email_success_rate  邮件发送成功率
         * email_open_rate  邮件打开率
         * user_click_rate 用户点击邮件率
         * single_user_rate 下单用户率
         * pay_user_rate  付费用户率
         * bounces_rate 弹回率
         * hard_bounces_rate 硬弹率
         * soft_bounces_rate 软弹率
         * complaint_rate 投诉率
         * unsubscribe_rate 退订率
         */
        if ( ! (empty($totalTrans['order_amount']) ||
            empty($totalTrans['pay_order_amount']))) {
            $totalTrans['pay_amount_rate'] = round(100 * $totalTrans['pay_order_amount'] / $totalTrans['order_amount'],2);
        }

        if ( ! (empty($totalTrans['pay_order_num']) ||
            empty($totalTrans['order_num']))) {
            $totalTrans['pay_order_rate'] = round(100 * $totalTrans['pay_order_num'] / $totalTrans['order_num'],2);
        }
        if ( ! (empty($totalTrans['send_email_success_num']) ||
            empty($totalTrans['send_email_num']))) {
            $totalTrans['email_success_rate'] = round(100 *
                $totalTrans['send_email_success_num'] / $totalTrans['send_email_num'],2);
        }
        if ( ! (empty($totalTrans['email_open_num']) ||
            empty($totalTrans['send_email_success_num']))) {
            $totalTrans['email_open_rate'] = round(100 * $totalTrans['email_open_num'] / $totalTrans['send_email_success_num'],2);
        }

        if ( ! (empty($totalTrans['user_click_num']) ||
            empty($totalTrans['email_open_num']))) {
            $totalTrans['user_click_rate'] = round(100 * $totalTrans['user_click_num'] / $totalTrans['email_open_num'],2);
        }
        if ( ! (empty($totalTrans['single_user_num']) ||
            empty($totalTrans['user_click_num']))) {
            $totalTrans['single_user_rate'] = round(100 * $totalTrans['single_user_num'] / $totalTrans['user_click_num'],2);
        }
        if ( ! (empty($totalTrans['pay_user_num']) ||
            empty($totalTrans['single_user_num']))) {
            $totalTrans['pay_user_rate'] = round(100 * $totalTrans['pay_user_num'] / $totalTrans['single_user_num'],2);
        }

        $totalTrans['bounces_num'] =  $totalTrans['hard_bounces_num']+ $totalTrans['soft_bounces_num'];
        if ( ! (empty($totalTrans['bounces_num']) ||
            empty($totalTrans['send_email_num']))) {
            $totalTrans['bounces_rate'] = round(100 * $totalTrans['bounces_num'] / $totalTrans['send_email_num'],2);
        }

        if ( ! (empty($totalTrans['hard_bounces_num']) ||
            empty($totalTrans['bounces_num']))) {
            $totalTrans['hard_bounces_rate'] = round(100 * $totalTrans['hard_bounces_num'] / $totalTrans['bounces_num'],2);
        }

        if ( ! (empty($totalTrans['soft_bounces_num']) ||
            empty($totalTrans['bounces_num']))) {
            $totalTrans['soft_bounces_rate'] = round (100 * $totalTrans['soft_bounces_num'] / $totalTrans['bounces_num'],2);
        }
        if ( ! (empty($totalTrans['complaint_num']) ||
            empty($totalTrans['send_email_success_num']))) {
            $totalTrans['complaint_rate'] = round (100 * $totalTrans['complaint_num'] / $totalTrans['send_email_success_num'],2);
        }
        if ( ! (empty($totalTrans['unsubscribe_num']) ||
            empty($totalTrans['send_email_success_num']))) {
            $totalTrans['unsubscribe_rate'] =round( 100 * $totalTrans['unsubscribe_num'] / $totalTrans['send_email_success_num'],2);
        }

        if ( ! (empty($totalTrans['mailbox_unsubscribe_num']) ||
            empty($totalTrans['unsubscribe_num']))) {
            $totalTrans['mailbox_unsubscribe_rate'] = round(100 * $totalTrans['mailbox_unsubscribe_num'] / $totalTrans['unsubscribe_num'],2);
        }
        if ( ! (empty($totalTrans['mail_unsubscribe_num']) ||
            empty($totalTrans['unsubscribe_num']))) {
            $totalTrans['mail_unsubscribe_rate'] =round(100 *  $totalTrans['mail_unsubscribe_num'] / $totalTrans['unsubscribe_num'],2);
        }
        self::destroyMongo();

        $skuList = self::skuDimension(['group_id'=>$group_id]);
        // 品类相关数据
        $categoryList = self::categoryDimension(['group_id'=>$group_id]);

        // 下单用户相关数据
        $singleUserList = self::userDimension(['group_id'=>$group_id]);
        $openandclick  = self::openAndclick(['group_id' => $group_id]);
        $orderDivision = self::orderDivision(['group_id' => $group_id]);
        $countryList   = self::countryDimension(['group_id' => $group_id]);
        $response['totalTrans'] = $totalTrans;
        $response['single']['sku'] = $skuList;
        $response['single']['country'] = $countryList;
        $response['single']['category'] = $categoryList;
        $response['single']['single_user'] = $singleUserList;
        $response['terminal']['open'] = $openandclick['open'];
        $response['terminal']['complain'] = $openandclick['complain'];
        $response['terminal']['single'] =  $orderDivision;

        return $response;
    }

    /**
     *  打开和点击分析
     *  $data[
     *  group_id => '',
     *  email_type => '',
     * 'is_click' => '全选传此参数，0 为点击，1点击'
     *
     */

    public function openAndclick($data) {
        if (empty($data['group_id'])) {
            return [];
        }
        $table = $this->prefix.$data['group_id'];
        self::initMongo();
        $db =  $this->mongodb->$table;
        $match = ['open_count'=>['$gte'=>1]];
        $tmp =[];
        if (isset($data['email_type'])) {
            $tmp +=['email_type' => $data['email_type']];
        }
        if(isset($data['is_click'])) {
//            $tmp += ['is_click' => $data['is_click']];
            if (empty($data['is_click'])) { //未点击，为不等于1的
                $tmp += ['is_click' => ['$ne' =>"1"]];
            } else {
                $tmp += ['is_click' => $data['is_click']];
            }
        }
        if (! empty($tmp)) {
            $match += $tmp;
        }
        $group = ['$group'=>['_id' =>'$open_teminal','num'=>['$sum'=>1]]];
        $cond[] = ['$match'=>$match];
        $cond[] = $group;

        $orderInfo = $db->aggregate($cond)['result']; //['_id' =>'open_teminal 设备类型','num' =>'此类型数量']
        /*
         *
         *  'open' => [
                'amount' => 100,          // 数量
                'terminal' =>[
                   ['nmae' => 'web','value' => 30],
                    ['name' => 'ios','value' => 70]
                ]
            ]
         *
         */
        //设备类型 0：other 1：ios 2：android 3：pc
        $open =  [
            'sum' => 0,          // 数量
            'terminal' =>[
                ['name' => 'other','value' => "0"]
            ]];
        $terminal = [];
        if (! empty($orderInfo)) {
            foreach ( $orderInfo as $item) {
                $open['sum'] += $item['num'];
            }
            foreach ( $orderInfo as $key => $item) {
//                $terminal[$key]['value'] = $item['num'];
                //$terminal[$key]['rate'] = $item['num'] * 100 / $open['sum'];
                if ( ! isset($this->openDiviceName[$item['_id']])) {
                    if (isset($terminal[$this->openDiviceName['0']]['value'])) {
                        $terminal[$this->openDiviceName['0']]['value'] += $item['num'];
                    }else {
                        $terminal[$this->openDiviceName['0']]['value'] = $item['num'];
                    }
                    $terminal[$this->openDiviceName['0']]['name'] = $this->openDiviceName['0'];
                    // $terminal[$key]['name'] = $this->openDiviceName['0'];
                    continue;
                }
//                $terminal[$key]['name'] = $this->openDiviceName[$item['_id']];
                $terminal[$this->openDiviceName[$item['_id']]]['value'] = $item['num'];
                $terminal[$this->openDiviceName[$item['_id']]]['name'] = $this->openDiviceName[$item['_id']];
            }
            //$open['terminal'] = $terminal;
            $open['terminal'] = self::resetIndex($terminal);
        }

        /*
          'complain' =>[                // 邮件投诉
                'sum' => 100,          // 数量
                'terminal' =>[
                   ['nmae' => 'web','value' => 30],    //value
                   ['name' => 'ios','value' => 70]
                ]
            ]
         */
        $complain =  [
            'sum' => 0,          // 数量
            'terminal' =>[
                ['name' => 'other','value' => "0"],
            ]];
        // 退订
        $unsubCond[] = ['$match' => ['$or'=>[['is_unsubscribe'=>'1'],['mailbox_unsubscribe' =>'1'],['is_complaint'=>'1']]]];
        $unsubCond[] = ['$group'=>['_id' =>'$open_teminal','num'=>['$sum'=>1]]];

        if (! empty($tmp)) {
            $unsubCond[0]['$match'] += $tmp;
        }
        $temp = [];
        $unsubInfo = $db->aggregate($unsubCond)['result'];    //['_id' =>'open_teminal 设备类型','num' =>'此类型数量']
        if (! empty($unsubInfo)) {
            foreach ( $unsubInfo as $item) {
                $complain['sum'] += $item['num'];
            }
            foreach ( $unsubInfo as $key => $item) {

                if ( ! isset($this->openDiviceName[$item['_id']])) {
                    if (isset($temp[$this->openDiviceName['0']]['value'])) {
                        $temp[$this->openDiviceName['0']]['value'] += $item['num'];
                    }else {
                        $temp[$this->openDiviceName['0']]['value'] = $item['num'];
                    }
                    $temp[$this->openDiviceName['0']]['name'] = $this->openDiviceName['0'];
                    continue;
                }
                $temp[$this->openDiviceName[$item['_id']]]['value'] = $item['num'];
                $temp[$this->openDiviceName[$item['_id']]]['name'] = $this->openDiviceName[$item['_id']];
            }
            //  $complain['terminal'] = $terminal;
            $complain['terminal'] = self::resetIndex($temp);
        }

        $response['open'] = $open;
        $response['complain'] = $complain;
        self::destroyMongo();
        return $response;
    }
    /**
     * 重置key
     */
    public function resetIndex($info) {
        if (empty($info)) {
            return [];
        }
        $res = null;
        $key = 0;
        foreach ($info as $index => $val) {
            $res[$key] = $val;
            ++$key;
        }
        return $res;
    }

    /**
     *  邮件下单终端分布
     *  group_id
     *  pay_status 支付状态，0 未支付，1已支付
     */
    public function orderDivision($data) {
        if (empty($data['group_id'])) {
            return [];
        }
        $table = $this->prefix.$data['group_id'];
        self::initMongo();
        $db =  $this->mongodb->$table;
        $match = [];
        if (isset($data['pay_status'])) {
            if (empty($data['pay_status'])) {
                $match +=['orders.pay_status' => $data['pay_status']];
            } else {
                $match +=['orders.pay_status' => ['$gte' =>"1"]];    //大于等于1 为已支付状态
            }
        }else{
            $match +=['orders.pay_status' => ['$gte' =>"0"]];    //大于等于1 为已支付状态
        }
        $cond[] = ['$unwind'=>'$orders'];
        if (! empty($match)) {
            $cond[] = ['$match'=>$match];
        }
        $orderInfo = $db->aggregate($cond)['result']; //['_id' =>'open_teminal 设备类型','num' =>'此类型数量']
        /*
         *
         *  'open' => [
                'amount' => 100,          // 数量
                'terminal' =>[
                   ['nmae' => 'web','value' => 30],
                    ['name' => 'ios','value' => 70]
                ]
            ]
         */
        //设备类型 0：other 1：ios 2：android 3：pc
        $single =  [
            'sum' => 0,          // 数量
            'terminal' =>[
                ['name' => 'web','value' => "0"]
            ]];
        $terminal = [];

        $orderIndex = [];
        if (! empty($orderInfo)) {
            foreach ( $orderInfo as $key => $item) {
                if (! isset($item['orders'])) {
                    continue;
                }
                $orders = $item['orders'];
                if (! isset($orderIndex[$orders['order_sn']])) {
                    ++$single['sum'];
                    $orderIndex[$orders['order_sn']] = $orders['order_sn'];
                    //其它的异常处理
                    if ( ! isset($this->singleDeviceName[$orders['single_terminal']])) {
                        if (! isset( $terminal[$this->singleDeviceName['0']]['value'])) {
                            $terminal[$this->singleDeviceName['0']]['name'] = $this->singleDeviceName['0'];
                            $terminal[$this->singleDeviceName['0']]['value'] = 0;
                        }
                        ++$terminal[$this->singleDeviceName['0']]['value'];
                        continue;
                    }
                    if (isset($terminal[$this->singleDeviceName[$orders['single_terminal']]]['value'])) {
                        $terminal[$this->singleDeviceName[$orders['single_terminal']]]['value'] += 1;
                    }else {
                        $terminal[$this->singleDeviceName[$orders['single_terminal']]]['value'] =1;
                        $terminal[$this->singleDeviceName[$orders['single_terminal']]]['name'] = $this->singleDeviceName[$orders['single_terminal']];
                    }
                }
            }
            $single['terminal'] = self::resetIndex($terminal);
        }
        self::destroyMongo();
        return $single;
    }



    /**
     *  邮件下单终端分布
     *  group_id
     *  pay_status 支付状态，0 未支付，1已支付
     */
    public function actionOrderDivision() {
        $post = $_REQUEST;
        if ( ! isset($post['group_id']) || empty($post['group_id'])) {
            $this->error('group_id 不能为空');
        }
        if(isset($post['pay_status']) &&  is_numeric($post['pay_status'])) {
            $cond['pay_status'] = $post['pay_status'];
        }
        $cond['group_id'] = $post['group_id'];
//         $res = self::orderDivision(['group_id'=>15571]);
        $res = self::orderDivision($cond);
        if (empty($res)) {
            $this->error();
        }
        $this->success($res);
    }


    /**
     * group_id
     * email_type 邮件类型
     * is_click '全选传此参数，0 为点击，1点击'
     */

    public function actionOpenAndClickAnalysis() {
        $post = $_REQUEST;
        if ( ! isset($post['group_id']) || empty($post['group_id'])) {
            $this->error('group_id 不能为空');
        }
        $cond['group_id'] = $post['group_id'];
        if(isset($post['email_type']) && ! empty($post['email_type'])) {
            $cond['email_type'] = $post['email_type'];
        }
        if(isset($post['is_click']) && is_numeric($post['is_click'])) {
            $cond['is_click'] = (string)$post['is_click'];
        }
//        $res = self::openAndclick(['group_id'=>15571,'email_type' =>'5','is_click'=>'1']);
        $res = self::openAndclick($cond);
        if (empty($res)) {
            $this->error();
        }
        $this->success($res);
    }
     /**
     * 下单用户维度
     * yumao
     * 2018-6-18
     */
    public function userDimension($data)
    {
        if (empty($data['group_id'])) {
            return [];
        }

        $table = $this->prefix.$data['group_id'];
        self::initMongo();
        $db = $this->mongodb->$table;
        // 查出下单的用户
        $singleUserArr = $db->distinct("user_id",['orders'=>['$exists'=>"true"]]);
        $singleUserCount = count($singleUserArr);
        if (!$singleUserCount) {
           return [];
        }
        // 查出发送未打开用户数
        $sendNotOpenUserArr = $db->distinct("user_id",[
            'orders'=>['$exists'=>"true"],
            'open_email_count'=>['$lte'=>"1"],
            'send_email_count'=>['$gte'=>"2"]
            ]
        );
        $sendNotOpenUserCount = count($sendNotOpenUserArr);

        // 查出已下单用户数
        $sendHaveOrderUserArr = $db->distinct("user_id",[
            'orders'=>['$exists'=>"true"],
            'order_count'=>['$gte'=>"2"]]
        );
        $sendHaveOrderUserCount = count($sendHaveOrderUserArr);

        // 点击未下单用户数
        $clickNotOrderUserArr = $db->distinct("user_id",[
            'orders'=>['$exists'=>"true"],
            'order_count'=>['$lte'=>"1"],
            'click_email_count'=>['$gte'=>"2"]]
        );
        $clickNotOrderUserCount = count($clickNotOrderUserArr);

        // 打开未点击
        $openNotClickUserArr = $db->distinct("user_id",[
            'orders'=>['$exists'=>"true"],
            'click_email_count'=>['$lte'=>"1"],
            'open_email_count'=>['$gte'=>"2"]]
        );
        $openNotClickUserCount = count($openNotClickUserArr);

        // 首次发邮件
        $firstSendUserArr = $db->distinct("user_id",[
            'orders'=>['$exists'=>"true"],
            'send_email_count'=>['$lte'=>"1"]]
        );
        $firstSendUserCount = count($firstSendUserArr);

        // 首次购买
        $firstOrderUserArr = $db->distinct("user_id",[
            'orders'=>['$exists'=>"true"],
            'order_count'=>['$lte'=>"1"]]
        );
        $firstOrderUserCount = count($firstOrderUserArr);

        // 复购
        $rebackOrderUserArr = $db->distinct("user_id",[
            'orders'=>['$exists'=>"true"],
            'order_count'=>['$gte'=>"2"]]
        );
        $rebackOrderUserCount = count($rebackOrderUserArr);

        // 各种率
        $singUserLv = [];
//        $singUserLv['sendNotOpenUserLv'] =  round(100 *  $sendNotOpenUserCount /  $singleUserCount,2);
//        $singUserLv['sendHaveOrderUserLv'] =  round(100 *  $sendHaveOrderUserCount /  $singleUserCount,2);
//        $singUserLv['clickNotOrderUserLv'] =  round(100 *  $clickNotOrderUserCount /  $singleUserCount,2);
//        $singUserLv['openNotClickUserLv'] =  round(100 *  $openNotClickUserCount /  $singleUserCount,2);
//        $singUserLv['firstSendUserLv'] =  round(100 *  $firstSendUserCount /  $singleUserCount,2);
//        $singUserLv['firstOrderUserLv'] =  round(100 *  $firstOrderUserCount /  $singleUserCount,2);
//        $singUserLv['rebackOrderUserLv'] =  round(100 *  $rebackOrderUserCount /  $singleUserCount,2);
        $singUserLv['sendNotOpenUser'] =  $sendNotOpenUserCount;
        $singUserLv['sendHaveOrderUser'] =  $sendHaveOrderUserCount;
        $singUserLv['clickNotOrderUser'] =$clickNotOrderUserCount ;
        $singUserLv['openNotClickUser'] = $openNotClickUserCount;
        $singUserLv['firstSendUser'] =  $firstSendUserCount ;
        $singUserLv['firstOrderUser'] =  $firstOrderUserCount ;
        $singUserLv['rebackOrderUser'] =  $rebackOrderUserCount;
        return $singUserLv;
    }

    /**
     * 品类维度
     * yumao
     * 2018-6-18
     */
    public function categoryDimensionOld($data)
    {
        if (empty($data['group_id'])) {
            return [];
        }
        $table = $this->prefix.$data['group_id'];
        self::initMongo();
        $db = $this->mongodb->$table;

        $orderList = $db->find(["orders"=>['$exists'=>"true"]],['orders'=>1,'_id'=>0]);

        $orderList = iterator_to_array($orderList);

        self::destroyMongo();
        if (empty($orderList)) {   //没有更多信息
            return [];
        }

        $categoryList = []; // 品类为维度
        $categoryListUserArr = []; // 根据品类记录用户id
        foreach ($orderList as $val) {
            if (!is_array($val['orders']) || !isset($val['orders'][0]['goods_sn'])) {
                continue;
            }

            // 保存当前订单包含的所有品类
            $orderCategory = [];

            // 保存当前订单包含的所有付款品类
            $orderPayCategory = [];


            foreach ($val['orders'] as $v) {
                if (!isset($v['goods_sn'])) {
                    continue;
                }

                if( empty($categoryListUserArr[$v['category_id']]) || !in_array($v['user_id'],$categoryListUserArr[$v['category_id']])) {
                    $categoryListUserArr[$v['category_id']][] = $v['user_id'];
                }

                // 记录当前订单的品类
                if (!in_array($v['category_id'],$orderCategory)) {
                    $orderCategory[] = $v['category_id'];
                }

                // 记录当前订单的付款品类
                if ($v['pay_status'] >= 1) {
                    if (!in_array($v['category_id'],$orderPayCategory)) {
                        $orderPayCategory[] = $v['category_id'];
                    }
                }

                // 根据品类记录订单金额
                if (!empty($categoryList[$v['category_id']]['order_amount'])) {
                    $categoryList[$v['category_id']]['order_amount'] += $v['order_amount'];
                } else {
                    $categoryList[$v['category_id']]['order_amount'] = $v['order_amount'];
                }
                $categoryList[$v['category_id']]['category_name'] = $v['category_name'];
                // 记录付款订单金额
               if ($v['pay_status'] >= 1) {
                   if (!empty($categoryList[$v['category_id']]['pay_order_amount'])) {
                        $categoryList[$v['category_id']]['pay_order_amount'] += $v['order_amount'];
                    } else {
                        $categoryList[$v['category_id']]['pay_order_amount'] = $v['order_amount'];
                    }
                }


                // 根据品类记录商品数量
                if (!empty($categoryList[$v['category_id']]['order_goods_num'])) {
                    $categoryList[$v['category_id']]['order_goods_num'] += $v['goods_number'];
                } else {
                    $categoryList[$v['category_id']]['order_goods_num'] = $v['goods_number'];
                }
            }

            // 根据品类记录订单数量
            foreach ($orderCategory as $orderCategoryVal) {
                if (!empty($categoryList[$orderCategoryVal]['order_num'])) {
                    $categoryList[$orderCategoryVal]['order_num']++; // 当前品类订单数加1
                } else {
                    $categoryList[$orderCategoryVal]['order_num'] = 1;
                }
            }

            // 根据品类记录付款订单数量
            foreach ($orderPayCategory as $orderCategoryVal) {
                if (!empty($categoryList[$orderCategoryVal]['pay_order_num'])) {
                    $categoryList[$orderCategoryVal]['pay_order_num']++; // 当前品类付款订单数加1
                } else {
                    $categoryList[$orderCategoryVal]['pay_order_num'] = 1;
                }
            }

            // 记录当前订单的品类用户数

        }

        foreach ($categoryList as $categoryListKey=>$categoryListVal) {
            // 用户数据
            if (!empty($categoryListUserArr[$categoryListKey])) {
                $categoryList[$categoryListKey]['single_user_num'] = count($categoryListUserArr[$categoryListKey]);
            }

            // 计算付款金额率和付款订单率
             if ( ! (empty($categoryList[$categoryListKey]['order_num']) || empty($categoryList[$categoryListKey]['pay_order_num']))) {
                $categoryList[$categoryListKey]['pay_order_rate'] = round(100 * $categoryList[$categoryListKey]['pay_order_num'] / $categoryList[$categoryListKey]['order_num'],2);
            } else {
                $categoryList[$categoryListKey]['pay_order_rate'] = 0.0;
            }

            if ( ! (empty($categoryList[$categoryListKey]['pay_order_amount']) || empty($categoryList[$categoryListKey]['order_amount']))) {
                $categoryList[$categoryListKey]['pay_amount_rate'] =round(100 *  $categoryList[$categoryListKey]['pay_order_amount'] /  $categoryList[$categoryListKey]['order_amount'],2);
            } else {
                $categoryList[$categoryListKey]['pay_amount_rate'] = 0.0;
            }
        }

        // 处理分类数据
//        echo '<pre>';
//        var_dump($categoryList);
//        echo '<br>------------------------------------------<br>';
       $categoryList =  self::resetIndex($categoryList);
//       var_dump($categoryList);
//        exit;
        return $categoryList;
    }



    /**
     *  sku 为维度
     *  group_id
     *  $page = 0
     *  $pageSize = 10
     *  authore xianxuefeng
     */
    public function categoryDimension($data) {
        if (empty($data['group_id'])) {
            return [];
        }
        $table = $this->prefix.$data['group_id'];
        self::initMongo();
        $db = $this->mongodb->$table;
        $orderList = $db->find(["orders"=>['$exists'=>"true"]],['orders'=>1,'_id'=>0]);

        $orderList = iterator_to_array($orderList);

        self::destroyMongo();
        if (empty($orderList)) {   //没有更多信息
            return [];
        }
        /*
           [
                'goods_sn' => $val['_id'],
                'category_id' => $val['category_id'][0],
                'order_num' => 0,
                'order_amount' =>0,
                'pay_order_num' => 0,
                'pay_order_amount' =>0,
                'single_user_num' => 0,
                'pay_order_rate' => 0,
                'pay_amount_rate' => 0
            ]
         */

        $skuList = [];
        $orderIndex = [];
        foreach($orderList as $val) {
            if (!isset($val['orders'][0]['goods_sn']) || !is_array($val['orders'])) {
                continue;
            }
            foreach ($val['orders'] as $v) {
                if (!isset($v['goods_sn'])) {
                    continue;
                }
                //skuList[goods_sn] 为空时，初始化
                if (!isset($skuList[$v['category_id']])) {
                    $skuList[$v['category_id']]['goods_sn'] = $v['goods_sn'];
                    $skuList[$v['category_id']]['category_id'] = $v['category_id'];
                    $skuList[$v['category_id']]['category_name'] =isset($v['category_name'])? $v['category_name']: '';
                    $skuList[$v['category_id']]['order_goods_num'] = 0;
                    $skuList[$v['category_id']]['goods_name'] = $v['goods_name'];
                    $skuList[$v['category_id']]['order_num'] = 0;
                    $skuList[$v['category_id']]['order_amount'] = 0;
                    $skuList[$v['category_id']]['pay_order_num'] = 0;
                    $skuList[$v['category_id']]['pay_order_amount'] = 0;
                    $skuList[$v['category_id']]['single_user_num'] = 1;    //初始化订单用户数
                    $skuList[$v['category_id']]['pay_order_rate'] = 0;    // 支付订单率
                    $skuList[$v['category_id']]['pay_amount_rate'] = 0;    //支付订单金额率
                    $skuList[$v['category_id']]['pay_single_user_num'] = 0;    //支付订单用户数默认为1
                }
                $skuList[$v['category_id']]['user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                if (isset($orderIndex[$v['order_sn']])) {     //去除重复的订单
                    continue;
                }
                $orderIndex[$v['order_sn']] = $v['order_sn'];
                ++$skuList[$v['category_id']]['order_num'];
                $skuList[$v['category_id']]['order_amount'] += $v['order_amount'];
                $skuList[$v['category_id']]['order_goods_num'] += isset($v['goods_number'])? $v['goods_number'] : 0;
                if ($v['pay_status'] >= 1) {   //支付订单
                    $skuList[$v['category_id']]['pay_user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                    ++$skuList[$v['category_id']]['pay_order_num'];
                    $skuList[$v['category_id']]['pay_order_amount'] += $v['order_amount'];
                }
            }
        }
        unset($data,$table,$db,$orderList);
        // 统计支付订单的订单率和金额率
        foreach ( $skuList as & $val) {
            $val['single_user_num'] = isset($val['user_id_array']) ? count($val['user_id_array']) : 0;            // 下单用户数
            $val['pay_single_user_num'] =isset($val['pay_user_id_array']) ? count($val['pay_user_id_array']) : 0;    // 支付订单用户数
            if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
            }
            if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2);
            }
            unset($val['user_id_array'],$val['pay_user_id_array']);
        }
        return self::resetIndex($skuList);
    }



    /**
     *  sku 为维度
     *  group_id
     *  $page = 0
     *  $pageSize = 10
     */
    public function skuDimensionOld($data) {
        if (empty($data['group_id'])) {
            return [];
        }
//        if (! isset($data['page'])) {
//            $data['page'] = 0;
//        }
        $table = $this->prefix.$data['group_id'];
        self::initMongo();
        $db = $this->mongodb->$table;
//        $page = $data['page'];
//        $pageSize = 5;
//        $limit = ($page+1) * $pageSize ;
//        $skip = $limit - $pageSize;    //偏移量
        // 分页获取唯一的sku
//         $orderList = $db->aggregate([
//             ['$unwind'=>'$orders'],
//             ['$group' =>['_id' =>'$orders.goods_sn',
//                 'category_id' =>['$push'=>'$orders.category_id']]],
//             ['$limit' => $limit],
//             ['$skip' => $skip]
//         ])['result'];
        $orderList = $db->aggregate([
            ['$unwind'=>'$orders'],
            ['$group' =>['_id' =>'$orders.goods_sn',
                'category_id' =>['$push'=>'$orders.category_id']]]
        ])['result'];

        if (empty($orderList) || ! isset($orderList[0]['category_id'])) {   //没有更多信息
            return [];
        }
        foreach($orderList as & $val) {
            $val=[
                'goods_sn' => $val['_id'],
                'category_id' => $val['category_id'][0],
                'order_num' => 0,
                'order_amount' =>0,
                'pay_order_num' => 0,
                'pay_order_amount' =>0,
                'single_user_num' => 0,
                'pay_order_rate' => 0,
                'pay_amount_rate' => 0
            ];

            $orderInfo = $db->aggregate([
                ['$unwind'=>'$orders'],
                ['$match' =>['orders.goods_sn'=>$val['goods_sn']]],
                ['$group' =>[
                    '_id'=>"",
                    'order_num' => ['$sum' =>1],
                    'order_amount' => ['$sum' => '$orders.order_amount']
                ]]])['result'];

            if (! empty($orderInfo)) {
                $val['order_num'] = $orderInfo[0]['order_num'];
                $val['order_amount'] = $orderInfo[0]['order_amount'];
            }
            $payOrderInfo = $db->aggregate([
                ['$unwind'=>'$orders'],
                ['$match' =>['orders.goods_sn'=>$val['goods_sn'],
                    'orders.pay_status' =>['$gte' => "1"]]],
                ['$group' =>[
                    '_id'=>"",
                    'pay_order_num' => ['$sum' =>1],
                    'pay_order_amount' => ['$sum' => '$orders.order_amount']
                ]]])['result'];
            if (! empty($payOrderInfo)) {
                $val['pay_order_num'] = $payOrderInfo[0]['pay_order_num'];
                $val['pay_order_amount'] = $payOrderInfo[0]['pay_order_amount'];
            }
            // 下单用户
            $orderUserInfo = $db->aggregate([
                ['$unwind'=>'$orders'],
                ['$match' =>['orders.goods_sn'=>$val['goods_sn']]],
                ['$group' =>[
                    '_id'=>'$user_id',
                    'single_user_num' => ['$sum' =>1]
                ]]])['result'];
            if (! empty($orderUserInfo)) {
                $val['single_user_num'] = $orderUserInfo[0]['single_user_num'];
            }
            if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
            }

            if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2);
            }
        }
        self::destroyMongo();
        return $orderList;
    }

    public function actionSkuTest() {
        $post = $_REQUEST;
        $group_id = 11802;
        if (isset($post['group_id'])) {
            $group_id = $post['group_id'];
        }
        if ( isset($post['type']) && ! empty($post['type'])) {
             $res = self::skuDimensionOld(['group_id'=>$group_id]);
        }else {

//             $res = self::skuDimension(['group_id'=>$group_id]);
             $res = self::countryDimensionTest(['group_id'=>$group_id]);
        }
        echo "<pre/>";
        print_r($res);die;
    }

    /**
     *  sku 为维度
     *  group_id
     *  $page = 0
     *  $pageSize = 10
     */
    public function skuDimension($data) {
        if (empty($data['group_id'])) {
            return [];
        }
        $table = $this->prefix.$data['group_id'];
        self::initMongo();
        $db = $this->mongodb->$table;
        $orderList = $db->find(["orders"=>['$exists'=>"true"]],['orders'=>1,'_id'=>0]);
        $orderList = iterator_to_array($orderList);
        self::destroyMongo();
        if (empty($orderList)) {   //没有更多信息
            return [];
        }
        /*
           [
                'goods_sn' => $val['_id'],
                'category_id' => $val['category_id'][0],
                'order_num' => 0,
                'order_amount' =>0,
                'pay_order_num' => 0,
                'pay_order_amount' =>0,
                'single_user_num' => 0,
                'pay_order_rate' => 0,
                'pay_amount_rate' => 0
            ]
         */

        $skuList = [];
        foreach($orderList as $val) {
            if (!isset($val['orders'][0]['goods_sn']) || !is_array($val['orders'])) {
                continue;
            }
            foreach ($val['orders'] as $v) {
                if (!isset($v['goods_sn'])) {
                    continue;
                }
                //skuList[goods_sn] 为空时，初始化
                if (!isset($skuList[$v['goods_sn']])) {
                    $skuList[$v['goods_sn']]['goods_sn'] = $v['goods_sn'];
                    $skuList[$v['goods_sn']]['category_id'] = $v['category_id'];
                    $skuList[$v['goods_sn']]['category_name'] =isset($v['category_name'])? $v['category_name']: '';
                    $skuList[$v['goods_sn']]['order_goods_num'] = 0;   //商品数量
                    $skuList[$v['goods_sn']]['goods_name'] = $v['goods_name'];
                    $skuList[$v['goods_sn']]['order_num'] = 0;
                    $skuList[$v['goods_sn']]['order_amount'] = 0;
                    $skuList[$v['goods_sn']]['pay_order_num'] = 0;
                    $skuList[$v['goods_sn']]['pay_order_amount'] = 0;
                    $skuList[$v['goods_sn']]['single_user_num'] = 1;    //初始化订单用户数
                    $skuList[$v['goods_sn']]['pay_order_rate'] = 0;    // 支付订单率
                    $skuList[$v['goods_sn']]['pay_amount_rate'] = 0;    //支付订单金额率
                    $skuList[$v['goods_sn']]['pay_single_user_num'] = 0;    //支付订单用户数默认为1
                }
                $skuList[$v['goods_sn']]['user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                ++$skuList[$v['goods_sn']]['order_num'];
                $skuList[$v['goods_sn']]['order_amount'] += $v['order_amount'];
                $skuList[$v['goods_sn']]['order_goods_num'] += isset($v['goods_number'])? $v['goods_number'] : 0;
                if ($v['pay_status'] >= 1) {   //支付订单
                    $skuList[$v['goods_sn']]['pay_user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                    ++$skuList[$v['goods_sn']]['pay_order_num'];
                    $skuList[$v['goods_sn']]['pay_order_amount'] += $v['order_amount'];
                }
            }
        }
        unset($data,$table,$db,$orderList);
        // 统计支付订单的订单率和金额率
        foreach ( $skuList as & $val) {
            $val['single_user_num'] = isset($val['user_id_array']) ? count($val['user_id_array']) : 0;            // 下单用户数
            $val['pay_single_user_num'] =isset($val['pay_user_id_array']) ? count($val['pay_user_id_array']) : 0;    // 支付订单用户数
            if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
            }
            if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2);
            }
            unset($val['user_id_array'],$val['pay_user_id_array']);
        }
        return self::resetIndex($skuList);
    }


    /**
     *  country 为维度
     *  group_id
     *  $page = 0
     *  $pageSize = 10
     */
    public function countryDimension($data) {
        if (empty($data['group_id'])) {
            return [];
        }
        $table = $this->prefix.$data['group_id'];
        self::initMongo();
        $db = $this->mongodb->$table;
        $orderList = $db->find(["orders"=>['$exists'=>"true"]],['orders'=>1,'_id'=>0]);
        $orderList = iterator_to_array($orderList);
        self::destroyMongo();
        if (empty($orderList)) {   //没有更多信息
            return [];
        }
        $countryList = [];
        $orderIndex = [];
        foreach($orderList as $val) {
            if (!isset($val['orders'][0]['country']) || ! is_array($val['orders'])) {
                continue;
            }
            foreach ($val['orders'] as $v) {
                if (!isset($v['country'])) {
                    continue;
                }
                //skuList[goods_sn] 为空时，初始化
                if (!isset($skuList[$v['country']])) {
                    $countryList[$v['country']]['country'] = $v['country'];
                    $countryList[$v['country']]['category_id'] = $v['category_id'];
                    $countryList[$v['country']]['order_num'] = 0;
                    $countryList[$v['country']]['order_amount'] = 0;
                    $countryList[$v['country']]['pay_order_num'] = 0;
                    $countryList[$v['country']]['pay_order_amount'] = 0;
                    $countryList[$v['country']]['single_user_num'] = 1;    //初始化订单用户数
                    $countryList[$v['country']]['pay_order_rate'] = 0;    // 支付订单率
                    $countryList[$v['country']]['pay_amount_rate'] = 0;    //支付订单金额率
                    $countryList[$v['country']]['pay_single_user_num'] = 0;    //支付订单用户数默认为1
                }
                if (isset($orderIndex[$v['order_sn']])) {     //去除重复的订单
                    continue;
                }
                $orderIndex[$v['order_sn']] = $v['order_sn'];
                $countryList[$v['country']]['user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                ++$countryList[$v['country']]['order_num'];
                $countryList[$v['country']]['order_amount'] += $v['order_amount'];
                if ($v['pay_status'] >= 1) {   //支付订单
                    $countryList[$v['country']]['pay_user_id_array'][$v['user_id']] = $v['user_id'];   // 下单用户数组
                    ++$countryList[$v['country']]['pay_order_num'];
                    $countryList[$v['country']]['pay_order_amount'] += $v['order_amount'];
                }
            }
        }
        unset($data,$table,$db,$orderList);
        // 统计支付订单的订单率和金额率
        foreach ( $countryList as & $val) {
            $val['single_user_num'] = isset($val['user_id_array']) ? count($val['user_id_array']) : 0;            // 下单用户数
            $val['pay_single_user_num'] =isset($val['pay_user_id_array']) ? count($val['pay_user_id_array']) : 0;    // 支付订单用户数
            if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
            }
            if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2);
            }
            unset($val['user_id_array'],$val['pay_user_id_array']);
        }
        return self::resetIndex($countryList);
        return $orderList;
    }

    /**
     *  sku 为维度
     *  group_id
     *  $page = 0
     *  $pageSize = 10
     */
    public function countryDimensionOld($data) {
        if (empty($data['group_id'])) {
            return [];
        }
//        if (! isset($data['page'])) {
//            $data['page'] = 0;
//        }
        $table = $this->prefix.$data['group_id'];
        self::initMongo();
        $db = $this->mongodb->$table;
//        $page = $data['page'];
//        $pageSize = 5;
//        $limit = ($page+1) * $pageSize ;
//        $skip = $limit - $pageSize;    //偏移量
        // 分页获取唯一的sku
//        $orderList = $db->aggregate([
//            ['$match' =>['country' =>['$ne'=>null]]],
//            ['$group' =>['_id' =>'$country']],
//            ['$limit' => $limit],
//            ['$skip' => $skip]
//        ])['result'];

        $orderList = $db->aggregate([
            ['$unwind' => '$orders'],
            ['$match' =>['orders.country' =>['$ne'=>null]]],
            ['$group' =>['_id' =>'$orders.country']]
        ])['result'];
        if (empty($orderList)) {   //没有更多信息
            return [];
        }
        foreach($orderList as & $val) {
            $val=[
                'country' => $val['_id'],
                'order_num' => 0,
                'order_amount' =>0,
                'pay_order_num' => 0,
                'pay_order_amount' =>0,
                'single_user_num' => 0,
                'pay_order_rate' => 0,
                'pay_amount_rate' => 0
            ];

            $orderInfo = $db->aggregate([
                ['$unwind'=>'$orders'],
                ['$match' =>['orders.country'=>$val['country']]],
                ['$group' =>[
                    '_id'=>"",
                    'order_num' => ['$sum' =>1],
                    'order_amount' => ['$sum' => '$orders.order_amount']
                ]]])['result'];
            if (! empty($orderInfo)) {
                $val['order_num'] = $orderInfo[0]['order_num'];
                $val['order_amount'] = $orderInfo[0]['order_amount'];
            }
            $payOrderInfo = $db->aggregate([
                ['$unwind'=>'$orders'],
                ['$match' =>['orders.country'=>$val['country'],
                    'orders.pay_status' =>['$gte' => "1"]]],
                ['$group' =>[
                    '_id'=>"",
                    'pay_order_num' => ['$sum' =>1],
                    'pay_order_amount' => ['$sum' => '$orders.order_amount']
                ]]])['result'];
            if (! empty($payOrderInfo)) {
                $val['pay_order_num'] = $payOrderInfo[0]['pay_order_num'];
                $val['pay_order_amount'] = $payOrderInfo[0]['pay_order_amount'];
            }
            // 下单用户
            $orderUserInfo = $db->aggregate([
                ['$unwind'=>'$orders'],
                ['$match' =>['orders.country'=>$val['country']]],
                ['$group' =>[
                    '_id'=>'$user_id',
                    'single_user_num' => ['$sum' =>1]
                ]]])['result'];
            if (! empty($orderUserInfo)) {
                $val['single_user_num'] = $orderUserInfo[0]['single_user_num'];
            }

            if ( ! (empty($val['order_num']) || empty($val['pay_order_num']))) {
                $val['pay_order_rate'] = round(100 * $val['pay_order_num'] / $val['order_num'],2);
            }

            if ( ! (empty($val['pay_order_amount']) || empty($val['order_amount']))) {
                $val['pay_amount_rate'] =round(100 * $val['pay_order_amount'] / $val['order_amount'],2) ;
            }
        }
        self::destroyMongo();
        return $orderList;
    }

    /**
     * sku 维度
     */
    public function actionSku() {
        $post = $_REQUEST;
        if ( ! isset($post['group_id']) || empty($post['group_id'])) {
            $this->error('group_id 不能为空');
        }
        if (! isset($post['page'])) {
            $post['page'] = 0;
        }

        $cond['group_id'] = $post['group_id'];
        $cond['page'] = $post['page'];

        $res = self::skuDimension($cond);
        if (empty($res)) {
            $this->error("没有更多信息了");
        }
        $this->success($res);
    }


    /**
     *  country 国家维度
     */
    public function actionCountry() {
        $post = $_REQUEST;
        if ( ! isset($post['group_id']) || empty($post['group_id'])) {
            $this->error('group_id 不能为空');
        }
        if (! isset($post['page'])) {
            $post['page'] = 0;
        }
        $cond['group_id'] = $post['group_id'];
        $cond['page'] = $post['page'];
        $res = self::countryDimension($cond);
//        $res = self::countryDimension(['group_id'=>15571]);
        if (empty($res)) {
            $this->error("没有更多信息了");
        }
        $this->success($res);
    }

    /**
     * 协议模拟数据
     *
     */
    public function actionTest() {
        $info['totalTrans'] = [                 // 邮件转化分析
            'order_amount' => 0,                // 订单总额
            'pay_order_amount' => 0,            // 付款总额 ,note :汇总统计该发送分组的已支付订单总金额, 币种为美元（$）。
            'order_num' => 0,                   // 订单数,note : 汇总统计该发送分组的所有订单数（单位：个），按订单号汇总
            'pay_order_num' => 0,            // 付款订单数 ,note : 汇总统计该发送分组的所有已支付订单数（单位：个），按订单号汇总。
            'pay_amount_rate' => 0,             // 付款金额率 ,note : 付款金额率=[付款总额/订单总额]*100%
            'pay_order_rate' => 0,              // 付款订单率 ,note : 付款订单率=[付款订单数/订单数] *100%
            'send_email_num' => 0,           // 邮件发送数量
            'send_email_success_num' => 0,   // 邮件发送成功的数量, note : 渠道返回的该发送分组发送成功用户数。
            'email_success_rate' => 0,          // 邮件发送成功率 , note :  渠道返回的该发送分组发送成功用户数。
            'email_open_num' => 0,           // 邮件打开的数量 , note : 取该发送分组的独立打开用户数
            'email_open_rate' => 0,             // 邮件打开率 , note : 打开率=[独立打开用户数/发送成功] *100%
            'user_click_num' => 0,           // 用户点击邮件数量（用户点击）, note : 取该发送分组的独立点击用户数
            'user_click_rate' => 0,             // 用户点击邮件率（用户点击率）, note : 点击转化率=[独立点击用户数/独立打开用户数] *100%
            'single_user_num' => 0,     // 下单用户数 (汇总统计该发送分组的下过订单的用户数（按网站用户ID汇总）)
            'single_user_rate' => 0,    // 下单用户率 (用户下单率=[独立点击用户数/独立打开用户数] *100%)
            'pay_user_num' => 0,     // 付费用户数(用户付款) ,note :汇总统计该发送分组的下过订单并且已支付的用户数（按网站用户ID汇总）
            'pay_user_rate' => 0,       // 付费用户率 note : 用户付款率=[用户付款 /用户下单] *100%
            'bounces_num' => 0,      // 弹回数 note: 弹回总数=硬弹用户数+软弹用户数
            'bounces_rate' => 0,        // 弹回率 note: 弹回率=[弹回总数/发送总量]*100%
            'hard_bounces_num' => 0, // 硬弹数
            'hard_bounces_rate' => 0,   // 硬弹率 note: 硬弹率=[硬弹用户数/弹回总数]*100%
            'soft_bounces_num' => 0, // 软弹数
            'soft_bounces_rate' => 0,   // 软弹率 note: 软弹率=[硬弹用户数/弹回总数]*100%
            'complaint_num' => 0,       // 投诉数
            'complaint_rate' => 0,      // 投诉率 note: 投诉率=[投诉用户数/发送成功数] *100%
            'unsubscribe_num' => 0,     // 退订数
            'unsubscribe_rate' => 0,    // 退订率 note: 投诉率=[投诉用户数/发送成功数] *100%
        ];

        $info['terminal'] = [             // 邮件打开、
            'open' => [
                'amount' => 100,          // 数量
                'terminal' =>[
                    ['nmae' => 'web','value' => 30],
                    ['name' => 'ios','value' => 70]
                ]
            ],
            'complain' =>[                // 邮件投诉
                'amount' => 100,          // 数量
                'terminal' =>[
                    ['nmae' => 'web','value' => 30],
                    ['name' => 'ios','value' => 70]
                ]
            ],
            'single' =>[                  // 下单
                'amount' => 100,          // 数量
                'terminal' =>[
                    ['nmae' => 'web','value' => 30],
                    ['name' => 'ios','value' => 70]
                ]
            ]
        ];

        $info['single'] = [          // 邮件下单分析
            'sku' => [[
                'goods_sn' => '0000',
                'goods_name' => '暂无名称',
                'category_id' => 12,  //分类id
                'category_name' => '分类名称',
                'single_user_num' => 100, //下单用户数
                'order_num' => 12,     // 订单数量
                'pay_order_amount' => 100,  //付费订单金额
                'pay_order_rate' => '20%', //付费订单率
                'order_amount' => 200,     //订单总金额
                'pay_amount_rate' => '30%', // 付款金额率 note:付款金额率=[付款总额/订单总额]*100%
            ]
            ],
            'category' =>[[
                'category_id' => 12, //商品分类
                'single_user_num' => 100, //下单用户数
                'order_num' => 12,     // 订单数量
                'pay_order_amount' => 100,  //付费订单金额
                'pay_order_rate' => '20%', //付费订单率
                'order_amount' => 200,     //订单总金额
                'pay_amount_rate' => '30%', // 付款金额率 note:付款金额率=[付款总额/订单总额]*100%
            ]],
            'single_user' =>[
                'order_rate' => '40%',  //已经下单率 note: 该发送分组的下单用户中历史已下单的用户占总下单用户比例
                'no_single_click_rate' => '30%', //点击未下单 note: 该发送分组的下单用户中历史点击邮件但未下单的用户占总下单用户比例
                'open unclick_rate' => '3%',     //打开未点击,note: 该发送分组的下单用户中历史打开未点击的用户占总下单用户比例
                'first_mail_rate' => '7%',       //首次发邮件, note: 该发送分组的下单用户中首次发邮件的用户占总下单用户比例
                'first_purchase_rate' => '10%',  //首次购买, note: 该发送分组的下单用户中首次购买的用户占总下单用户比例。首次购买指注册且下单频次为1的用户
                'buy_again_rate' => '10%',       //再次购买, note: 该发送分组的下单用户中下过2个订单以上的用户占总下单用户比例。复购注册且下单频次2以上的用户
            ],
            'country' => [
                'country_name' => '美国',
                'single_user_num' => 100, //下单用户数
                'order_num' => 12,     // 订单数量
                'pay_order_amount' => 100,  //付费订单金额
                'pay_order_rate' => '20%', //付费订单率
                'order_amount' => 200,     //订单总金额
                'pay_amount_rate' => '30%', // 付款金额率 note:付款金额率=[付款总额/订单总额]*100%
            ]
        ];
        $this->success($info);
    }

    public function actionEmailTypeList() {
        $email_type_list = [
            'others' => "1",
            'gmail'  => "2",
            "yahoo"  => "3",
            "hotmail" => "4",
            "live" =>"4",
            "aol"  => "5"
        ];
        $this->success($email_type_list);
    }


}